NumPy stands for Numerical Python.
NumPy is used for working for arrays.
Numpy are faster than lists because numpy arrays are stored at one continuous place in a memory.
Install NumPy
pip install numpy
Importing Numpy Module
import numpy
Create an array
import numpy as np l=[1, 2, 3] x=np.array(l) print(x)
Array dimensions
- 0-D array
- 1-D array
- 2-D array
import numpy as np x=np.array(0) print(type(x)) y=np.array([1, 2, 3]) print(type(y)) z=np.array([[1, 2],[3, 4]]) print(type(z))
Check number of dimensions of arrays
ndim
Array indexing
import numpy as np x=np.array([1, 2, 3, 4, 5]) print(x[0]) y=np.array([ [1, 2, 3], [4, 5, 6]]) print(y[1, 0 ])
Slicing in 2-D
y=np.array([ [1, 2, 3], [4, 5, 6]]) print(y[1, 0:2 ])
Shape of an array
Number of elements in each dimension
array.shape
Reshape an array
Reshape means changing dimension of array.
import numpy as np x=np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) print(x.reshape(2, 5))
Joining Numpy arrays
Concat more than one arrays together.
concatenate(arr1, arr2) import numpy as np x=np.array([1,2,3]) y=np.array([4,5,6]) z=np.concatenate((x,y)) print(z)
Iterating arrays.
Splitting numpy arrays
Break a single array into multiple arrays.
array_split(arr, number_of_array) import numpy as np x = np.array([1, 2, 3, 4, 5, 6]) y = np.array_split(x, 2) print(y)
Methods
dot() | Return product of two array |
import numpy as np x=np.array([ [1,2], [3,4]]) y=np.array([ [1,2], [3,4] ]) print(x.dot(y))
| |
max | Return max value from an array |
import numpy as np x=np.array([ [1,2], [3,4]]) print(x.max())
| |
min | Return minimum value fron an array |
import numpy as np x=np.array([ [1,2], [3,4]]) print(x.min())
prod | Return product of elements of given axis. |
import numpy as np x=np.array([ [1,2], [3,4]]) print(np.prod( x, axis=1 ))
sum() | Return sum of elements of given array |
import numpy as np x=np.array([ [1,2], [3,4]]) print(np.sum( x))