Ultimate Cheat-sheet to do numpy matrix operations like a boss

Numpy is a killer library- has everything you'll need for scientific computing with Python. However, the documentation reads like a dictionary- if you know the function, you can find the usage and syntax.

So here's a cheat-sheet to do the reverse: you find example & usage based on what you want to do.

  1. Get copy of array, casted to a specific type
  2. Get copy of array
  3. Get dot product of 2 arrays
  4. Get multiplicative inverse
  5. Get max along axis
  6. Get average along axis
  7. Get min along axis
  8. Get non-zero elements from array
  9. Multiply elements along row or column
  10. Change some value of an array in place
  11. Flatten an array totally or along an axis
  12. Repeat elements in array or across an axis
  13. Restructure an array into new array with different dimensions
  14. Round all values in an array to a given decimal precision
  15. Sort an array in place
  16. Find standard deviation or variance along an axis
  17. Save numpy array to file and load it back as array
  18. Convert array to nested python list
  19. Transpose an array
astype()
>>> x = np.array([1, 2, 2.5])
>>> x
array([ 1. ,  2. ,  2.5])  
>>> x.astype(int)
array([1, 2, 2])  
copy()
>>> x = np.array([[1,2,3],[4,5,6]], order='F')
>>> y = x.copy()
>>> x.fill(0)
>>> x
array([[0, 0, 0],  
       [0, 0, 0]])
>>> y
array([[1, 2, 3],  
       [4, 5, 6]])
dot()
>>> a = [[1,2],
         [3,6]]
>>> b = [[3,4],
         [5,7]]
>>> c = np.dot(a, b)
flatten()

Returns a flattened copy of the matrix.

>>> m = np.matrix([[1,2], [3,4]])
>>> m.flatten()
matrix([[1, 2, 3, 4]])  
getI()
>>> m = np.matrix('[1, 2; 3, 4]'); m
matrix([[1, 2],  
        [3, 4]])
>>> m.getI()
matrix([[-2. ,  1. ],  
        [ 1.5, -0.5]])
mean()

Returns the average of the matrix elements along the given axis.

>>> x = np.matrix(np.arange(12).reshape((3, 4)))
>>> x
matrix([[ 0,  1,  2,  3],  
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]])
>>> x.mean()
5.5  
>>> x.mean(0)
matrix([[ 4.,  5.,  6.,  7.]])  
>>> x.mean(1)
matrix([[ 1.5],  
        [ 5.5],
        [ 9.5]])
max()

Return the maximum value along an axis.

>>> x = np.matrix(np.arange(12).reshape((3,4))); x
matrix([[ 0,  1,  2,  3],  
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]])
>>> x.max()
11  
>>> x.max(0)
matrix([[ 8,  9, 10, 11]])  
>>> x.max(1)
matrix([[ 3],  
        [ 7],
        [11]])
min()

Returns the minimum value along an axis

x = np.matrix([[  0,  -1,  -2,  -3],  
        [ -4,  -5,  -6,  -7],
        [ -8,  -9, -10, -11]])
>>> x.min()
-11
>>> x.min(0)
matrix([[ -8,  -9, -10, -11]])  
>>> x.min(1)
matrix([[ -3],  
        [ -7],
        [-11]])
nonzero()

Returns indices of array where value is nonzero.

Example 1: Get non zero elements

>>> a = np.array([1,2,3,0,5,7])
>>> np.nonzero(a)
 (array([0, 1, 2, 4, 5]),)

>>> a[np.nonzero(a)]
array([1, 2, 3, 5, 7])  

Example 2: Get indices meeting certain criteria

>>> a = np.array([1,2,3,0,5,7])
>>> a > 3
array([False, False, False, False,  True,  True], dtype=bool)

# Since true is 1, false is 0, we can get indices meeting certain criteria
>>> np.nonzero(a>3)
(array([4, 5]),)
prod()

Multiply elements along any axis, or flatten and multiply

Example 1: Multiply all elements of array

>>> np.prod([[1,2],[3,4]])
24  

Example 2: Multiply along an axis

>>> np.prod([[1,2],[3,4]], axis=0)
array([3, 8])  
>>> np.prod([[1,2],[3,4]], axis=1)
array([2, 12])  
put()

Used to modify some values of an array in place.

>>> a = np.arange(5)
>>> np.put(a, 1, 99)
>>> a
array([0, 99, 2,   3,   4])  
>>> np.put(a, [0, 2], [-44, -55])
>>> a
array([-44,   1, -55,   3,   4])  
ravel()

Returns a flattened array.

>>> x = np.array([[1, 2, 3], [4, 5, 6]])
>>> print(np.ravel(x))
[1 2 3 4 5 6]
repeat()

Repeat elements in an array

Example 1: Repeat elements in simple array

>>> x = np.array([1, 2, 3, 5, 7])
>>> print(np.repeat(x, 2))
[1, 1, 2, 2, 3, 3, 5, 5, 7, 7]

Example 2: Repeat elements accross an axis

>>> a = np.array([[1,2],[3,4]])
>>> np.repeat(a, 2, axis=0) 
array([[1, 2],  
       [1, 2],
       [3, 4],
       [3, 4]])
>>> np.repeat(a, 2, axis=1) 
array([[1, 1, 2, 2],  
       [3, 3, 4, 4]])
reshape()

Gives a new shape to an array without changing its data. The total number of elements in the new dimension must be same

Example 1: Reshape simple array into multi dims

>>> x = np.array([1, 2, 3, 4, 5, 7])
>>> a.reshape((3,2))
array([[0, 1],  
       [2, 3],
       [4, 5]])

Example 2: Reduce dimensions using reshape

>>> a = np.array([[[1,2],[3,4]],[[5,6],[7,8]]])
>>> a.reshape((4,2))
array([[1, 2],  
       [3, 4],
       [5, 6],
       [7, 8]])
round()

Round all numbers in an array to a given number of decimal places.

>>> np.round([1.234, 1.556], 1)
array([ 1.2,  1.6])  
sort()

Get a copy of sorted array (or sorted along a direction)

# Example 1: Normal sort
>>> a = np.array([[1,4],[3,1]])
>>> np.sort(a)               
array([[1, 4],  
       [1, 3]])

# Example 2: Sort along flattened array
>>> np.sort(a, axis=None)     
array([1, 1, 3, 4])

# Example 3: Sort along the first axis
>>> np.sort(a, axis=0)        
array([[1, 1],  
       [3, 4]])
std()

Get standard deviation or variance of an entire array (or along an axis). Replace std() function with var() to get variance.

>>> a = np.array([[1, 2], [3, 4]])

Example 1: Std dev of entire array  
>>> np.std(a)
1.1180339887498949

Example 2: Std dev along an axis  
>>> np.std(a, axis=0)
array([ 1.,  1.])  
>>> np.std(a, axis=1)
array([ 0.5,  0.5])  
save() & load()

Save a np array to file and load it back.

>>> a = np.array([[1, 2], [3, 4]])

Example 1: Save an array to file  
>>> a = np.arange(5)
>>> a
array([0, 1, 2, 3, 4])  
>>> np.save('/tmp/temp.npy', a)

Example 2: load a file into array  
>>> b = np.load('/tmp/temp.npy')
>>> b
array([0, 1, 2, 3, 4])
tolist()

Convert numpy array to nested python list.

>>>> a = np.array([[[1,2],[3,4]],[[5,6],[7,8]]])
>>>> a.tolist()
[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
transpose()

Get transpose of the matrix.

>>> x = np.arange(4).reshape((2,2))
>>> x
array([[0, 1],  
       [2, 3]])
>>>
>>> np.transpose(x)
array([[0, 2],  
       [1, 3]])

Shivam

Read more posts by this author.

Subscribe to TrySudo

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!