Numpy Flashcards
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)