Numpy Flashcards
(35 cards)
create identity matrix of dimension n
a=np.eye(n)
convert a 1D array to a 3D array
a=np.array([i for i in range(27)]
y=a.reshape((3,3,3))
convert all elements of array from float to int, from binary to boolean
y=a.astype(‘int’)
y=a.astype(‘bool’)
From 2 numpy arrays, extract the indexes in which the elements in the 2 arrays match
print(np.where(a == b))
Output a sequence of equally gapped 5 numbers in the range 0 to 100
o = np.linspace(0, 100, 5)
Output a matrix (numpy array) of dimension 2-by-3 with each and every value equal to 5
o = np.full((2, 3), 5)
o=5*np.ones((2,3))
Output an array by repeating a smaller array of 2 dimensions, 10 times
o = np.tile(a, 10)
Output a 5-by-5 array of random integers between 0 (inclusive) and 10 (exclusive)
o=np.random.randint(0,10,(5,5))
Output a 3-by-3 array of random numbers following normal distribution
o = np.random.normal(size = (3,3)) #normal takes (mu,sigma,size)
Given 2 numpy arrays as matrices, output the result of multiplying the 2 matrices
o = a@b
also possible:
o = np.matmul(a, b)
Create a 1D array of numbers from 0 to 9
a=np.arange(10)
Create a 3×3 numpy array of all True’s
a=np.full((3,3), True, dtype=bool)
np.ones((3,3), dtype=bool)
Extract all odd numbers from arr
arr[arr % 2 == 1]
Replace all odd numbers in arr with -1
arr[arr % 2 == 1] = -1
Replace all odd numbers in arr with -1 without changing arr
out = np.where(arr % 2 == 1, -1, arr)
Convert a 1D array to a 2D array with 2 rows
arr.reshape(2, -1) # Setting to -1 automatically decides the number of rows or cols !!!!!!
Stack arrays a and b vertically
np. concatenate([a, b], axis=0)
np. vstack([a, b])
np. r_[a,b]
Stack arrays a and b horizontally
np. concatenate([a, b], axis=1)
np. hstack([a, b])
np. c_[a,b]
a = np.array([1,2,3])
Desired output:
array([1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3])
np.r_[np.repeat(a,3),np.tile(a,3)]
Get the common items between a and b
np.intersect1d(a,b)
From array a remove all items present in array b
np.setdiff1d(a,b)
Get the positions where elements of a and b match
np.where(a == b)
a[a==b]
Convert the function maxx that works on two scalars, to work on two arrays.
func=np.vectorize(scalar_func, otypes=[float]) func(a,b)
Swap columns 1 and 2 in the array arr.
arr[:, [1,0,2]]