Python Cheat Sheet: NumPy
“A puzzle a day to learn, code, and play” → Visit [Link]
Name Description Example
[Link] The shape attribute of NumPy array a keeps a tuple of a = [Link]([[1,2],[1,1],[0,0]])
integers. Each integer describes the number of elements of print([Link](a)) # (3, 2)
the axis.
[Link] The ndim attribute is equal to the length of the shape tuple. print([Link](a)) # 2
* The asterisk (star) operator performs the Hadamard product, a = [Link]([[2, 0
], [0, 2]])
i.e., multiplies two matrices with equal shape element-wise. b = [Link]([[1, 1 ], [1, 1]])
print(a*b) # [[2 0] [0 2]]
[Link](a,b), a@b The standard matrix multiplication operator. Equivalent to the print([Link](a,b))
@ operator. # [[2 2] [2 2]]
[Link]([start, ]stop, Creates a new 1D numpy array with evenly spaced values print([Link](0,10,2))
[step, ]) # [0 2 4 6 8]
[Link](start, stop, Creates a new 1D numpy array with evenly spread elements print([Link](0,10,3))
num=50) within the given interval # [ 0. 5. 10.]
[Link](a) Averages over all the values in the numpy array a = [Link]([[2, 0], [0, 2]])
print([Link](a)) # 1.0
<slice> = <val> Replace the <slice> as selected by the slicing operator with a = [Link]([0, 1, 0, 0
, 0])
the value <val>. a[::2] = 2
print(a) [2 1 2 0 2]
#
[Link](a) Calculates the variance of a numpy array. a = [Link]([2, 6])
print([Link](a)) # 4.0
[Link](a) Calculates the standard deviation of a numpy array print([Link](a)) # 2.0
[Link](a) Calculates the difference between subsequent values in fibs = [Link]([0, 1
, 1, 2, 3, 5])
NumPy array a print([Link](fibs, n=1))
# [1 0 1 1 2]
[Link](a) Calculates the cumulative sum of the elements in NumPy print([Link]([Link](5)))
array a. # [ 0 1 3 6 10]
[Link](a) Creates a new NumPy array with the values from a a = [Link]([10,3,7,1,0])
(ascending). print([Link](a))
# [ 0 1 3 7 10]
[Link](a) Returns the indices of a NumPy array so that the indexed a = [Link]([10,3,7,1,0])
values would be sorted. print([Link](a))
# [4 3 1 2 0]
[Link](a) Returns the maximal value of NumPy array a. a = [Link]([10,3,7,1,0])
print([Link](a)) # 10
[Link](a) Returns the index of the element with maximal value in the a = [Link]([10,3,7,1,0])
NumPy array a. print([Link](a)) # 0
[Link](a) Returns the indices of the nonzero elements in NumPy array a = [Link]([10,3,7,1,0])
a. print([Link](a)) # [0 1 2 3]