Cheat Sheet to NumPy

·

2 min read

Cheat Sheet to NumPy

This is an continuation of the series Data spell (that covers the topics of AI in the most practical and easy to understand terms)

Numpy - Numerical python is used for working with arrays. It becomes very useful while working with large high dimensional arrays for mathematical or logical operations .

How to use in your code ?

You can add NumPy into your python code by just importing it like any other package.

import numpy as np

there is no strict rule that you must use the alias as np , but its a convention around that developers use this , so i highly insist you to follow the same.

Create an array

arr = np.array([1,2,3])

# can also specify the datatype you want by  :
# arr = np.array([1,2,3],dtype = float)

Initialise arrays

  1. Create array of zeros

     zeros = np.zeros(5)
     # creates an 1 D array with 5 elements
     # you can specify the shape which you want
    
  1. Create arrays of ones

     ones = np.ones(10)
    
  2. Create Identity matrix

     matrix = np.eye(2)
    
     # creates 2 x 2 identity matrix
    

Create a range array

num = np.range(1,10)

Common operations

assume arr is an array.

Name of operationoperationsyntax
Transposeinterchanging the rows and columns of the original matrixarr.transpose() or arr.T
MeanAverage value of arrayarr.mean()
Sumsum of arrayarr.sum()
Sortreturn the given array in sorted orderarr.sort()

Conclusion

This was a brief introduction to NumPy, and there's much more to explore. For further details, you can read the official documentation here.