Numpy Flashcards
convert list to numpy array
np.array(list)
arange
np.arange(10,30)
Return evenly spaced values within a given interval.
zeros
np.zeros(count)
ones
np.ones(count)
linspace
np.linspace(0,10,3)
np.linspace(start,stop,count)
Return evenly spaced numbers over a specified interval.
eye
np.eye(4)
Creates an 4x4 identity matrix
array([[ 1., 0., 0., 0.],
[ 0., 1., 0., 0.],
[ 0., 0., 1., 0.],
[ 0., 0., 0., 1.]])
rand
np.random.rand(2)
Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1) .
np.random,rand(5,5)
creates 5x5 matrix with random float values 0-1
randn
np.random.randn(2) –> 2 values
np.random.randn(5,5)
creates 5x5 matrix with random float values.
Return a sample (or samples) from the “standard normal” distribution. Unlike rand which is uniform:
randint
np.random.randint(1,10)
Return random integers from low (inclusive) to high (exclusive). similar to random module
Reshape
array.reshape(5,5)
Returns an array containing the same data with a new shape.
argmax
arr = np.array([[3, 2, 1], [6, 5, 4], [9, 8, 7]])
np.argmax(arr)
# Find the indices of the maximum element along the flattened array
np.argmax(arr,axis = 0)
# Find the indices of the maximum element along the first axis (rows)
np.argmxax(arr, axis = 1)
# Find the indices of the maximum element along the second axis (columns)
argmax is a function that returns the indices of the maximum values along a given axis.
Shape
Shape is an attribute that arrays have (not a method) returns the shape of an array
dtype
You can also grab the data type of the object in the array:
Fetching the values from numpy array
arr[index]
arr[start : stop]
Broadcasting
arr[0:5]=100
copy
To get a copy, need to be explicit
arr.copy()
Indexing a 2D array (matrices) in numpy
The general format is arr_2d[row][col] or arr_2d[row,col].
arr_2d[1][0] == arr_2d[1,0]
2D array slicing in numpy
arr_2d[row,col]
arr_2d[:2,1:]
arr_2d[2,:]
Fancy Indexing in Numpy
arr2d = arr[[0., 0., 0., 0.],
[1., 1., 1., 1.],
[2., 2., 2., 2.],
[3., 3., 3., 3.]]
print(arr2d[[1,3]]) –> arr2d[[row1,row2,…]]
o/p
——
array([[1., 1., 1., 1.],
[3., 3., 3., 3.]])
Selection based on comparison operators
arr > 4
returns an array of true or false
boll_arr = array([False, True, False, False, True]
arr[boll_arr] == arr[arr>2]
returns values greater than 4
array([ 5, 6, 7, 8])
Arithematic operators on array
arr + arr
arr * arr
arr - arr
arr / arr
arr ** arr
Array functions
np.sqrt(arr)
np.exp(arr)
np.max(arr)
np.sin(arr)
np.log(arr)