NumPy: Python’s library

Bhargav Sharma
3 min readOct 9, 2022

Numpy: It’s a well-known library of python which brings the computational power of languages such as C and Fortran to python and facilitate advanced mathematical and other types of operations on a large number of data.

#can be installed using below command
pip install numpy

Important Features of NumPy:

  • Making powerful N-dimensional arrays that can perform additions, multiplications, and more. See how simple it is to add a 2-Dimensional array in the following code snippet.
import numpy as np
a=np.array([[1,2,3],[4,5,6]])
b=np.array([[-1,-2,-3],[-4,-5,-6]])
c=a+b #as simple as that
print(c)
Output:
[[0 0 0]
[0 0 0]]
  • NumPy offers comprehensive mathematical functions, random number generators, linear algebra routines, and more
  • NumPy supports a wide range of hardware and also plays well with distributed, GPU, and sparse libraries.
  • Easy to use.

Applications of NumPy:

  • Mathematics (MATLAB Replacement)
  • Plotting (Matplotlib)
  • Used in Pandas, Connect 4
  • Machine Learning

Some important and handy functions:

import numpy as np
  • Creating a NumPy array of specific datatype:
a=np.array([0,1,2],dtype='int16') #default dtype='int32'
b=np.array([[1,2,3],[0,-1,1]])
a.dtype #output: dtype('int16')
  • Dimensions and shapes of Numpy array:
a.ndim #ouptut: 1
b.ndim
#output: 2
a.shape
#output: (1,)
b.shape
#output: (2,3)
  • Size of NumPy array:
a.itemsize #output:4  -- size of int is 4 
b.itemsize
#output:4
a.nbytes #output:12 -- size*total_elements => 4*3=12
  • Accessing and changing specific elements, rows, columns, etc:
a[0,2] #output:2 --element at (0,2) in array a
b[0,:] #output:array([1,2,3])
b[:,2] #output:array([3,1])
b[0,startIndex:endIndex:stepSize] #output: accordingly
b[0,1]=2 #output: modifies the element at particular index
b[:,2]=[5] or [1,2] #ouput:for [5] it will changes the whole 2nd column with 5 and for 1,2 the column will be replaced by [1,2]
a[[1,2]] #output: returns data at index 1 and 2
  • Initializing different types of arrays:
np.zeros(2) #ouput:array([0.,0.]) these are of type 'float32'
np.zeros((2,3)) #ouput:array([[0.,0.,0.],[0.,0.,0.]])
#similarly np.ones()
np.full((1,1),99,dtype='float32')
#output:array([[99.],[99.]])
where as dtype is optional
np.full_like(a,4) #output:generates array of size a with element 4
np.random.rand(2,3) #output generates the array of random decimal number of given shape.
np.random.random_sample(a.shape) #output:similar to above but shape would be of a.
np.random.randint(low,high=None,size=None,dtype=int)#output generates the array of random integers number of given shape.
np.identity(3) #output creates identity matrix of size 3
np.arange(1,3,0.5) #output:array([1,1.5,2,2.5])generates an array for us from range 1 to 3 with step size 0.5
  • Important features of NumPy:
a=np.array([[0,1,2]])
b=np.array([[1,2,3],[0,-1,1]])
--AXIS
1. aixs=1:means along side [1,2,3] of b for first row
2. axis=0:means down side [1,
0] of b for first first column
np.sum(b,axis=0) #output: array([1,1,4])
np.sum(b,axis=1) #output: array([6,0])
np.repeat(a,3,axis=0) #output array([[0, 1, 2],[0, 1, 2],[0, 1, 2]])--By assigning the one array to another can lead it by referenceb=a
b[0,0]=20
#also changes the element in a
b=a.copy() #this could resolve the above problem
  • Mathematics:
a=np.array([[0,1,2]])
b=np.array([[1,2,3],[0,-1,1]])
a*=2 or a=a*2 #output:multiplies whole array by 2
a+=2 or a=a+2
a/=2 or a=a/2
a-=2 or a=a-2
a=a**2
#output:does the power of whole array by 2
a=np.cos(a) #output:sine values
a=np.sin(a) #output:cos values
  • Linear Algebra:
a=np.full((3,2),2) #output: array([[2,2],[2,2],[2,2]])
b=np.full((2,3),1) #output: array([[1,1,1],[1,1,1]])
c=a@b or np.dot(a,b) or np.matmul(a,b) #output all does the same work all are used for matrix multiplicationc=np.identitiy(3)
c=np.linalg.det(c) #output:1.0
# we can get eigenvalues,traces,inverse,SVD of a matrix through linalg
  • Statistics:
a=np.array([[0,1,2]])
b=np.array([[1,2,3],[0,4,1]])
np.min(a) #output: 0
np.max(b,axis=0) #output: array([1,4,3])
np.average()
np.mean()
np.sum()

.
.
.
  • Reorganizing Arrays:
a=np.array([[0,1,2]])
b=np.array([[1,2,3],[0,4,1]])
c=np.array([[2,1,2]])
new_b=b.reshape((6,1)) #output: array([1,2,3,0,4,1])
np.vstack([a,c]) #output: combines both as one array verticaly
np.hsatck([a,c]) #output: combines both as one array horizontaly
  • Miscellaneous:
--We can read data from file using NumPyfiledata=np.genfromtxt('data.txt',delimeter=',') 
#default datatype will be float
filedata.astype('int32')
--We can do boolean masking and advance indexing in files
filedata>50 #output:returns True or False on each index either greater than 50 or not.
filedata[filedata>50] #output: returns the elements which are greater than 50 in the file.
np.any(filedata>50,axis=0) #output:returns true by working for specific axis and returns true only if any one of the column is greater than 50 in the filenp.all(filedata>50,axis=0) #output:returns true by working for specific axis and returns true only if all elements in the column are greater than 50 in the file

Why to use NumPy over python Lists ?

Faster to read because of fewer bytes of memory (NumPy takes less memory than lists).

  • Consumes less memory.
import numpy as np
import sys
list= range(50)
numpyA= np.arange(50)
sys.getsizeof(list) #24
len(list) #50

print(sys.getsizeof(list)*len(list)) #1200
numpyA.itemsize #4
numpyA.size #50
print(numpyA.size*numpyA.itemsize) #200
  • Fast as compared to the list.

--

--

Bhargav Sharma

A student with a passion for technology and data-driven solutions.