NumPy — Programming at Multi Dimensions.
NumPy is a Python library that helps to deal with multi-dimensional arrays, matrices, vectors along high computational mathematical formulas and concepts. Wiki
Installing Numpy
Numpy is pre-installed in Google Colab. Here the code snippet of installing NumPy in Colaboratory.
!pip install numpy
Python List vs NumPy Array
A numpy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers. The number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving the size of the array along each dimension. A list is the Python equivalent of an array, but is resizeable and can contain elements of different types.[1]
import numpy as np
a = np.array([[1,2,3],[1,2,3],[4,5,6]])
Why Numpy Arrays over Python Lists?
- Size — Numpy data structures take up less space
- Performance — they have a need for speed and are faster than lists
- Functionality — SciPy and NumPy have optimized functions such as linear algebra operations built in.
Numpy Basic Operations
- Creating an array with zeros
array_zeros = np.zeros(4)
- Creating an array with ones
array_ones = np.ones(4)
- Creating an Empty Array
array_empty = np.empty(4)
- Creating Identity Matrices
ip: i = np.identity(3)
iop:array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])
- Multiplying Matrices
ip:array_a = np.array([[1,2],[3,4]]) array_b = np.array([[1,2],[3,4]]) dot_product = np.dot(array_a,array_b)
cross_product = np.cross(array_a, array_b) dot_product
cross_productop: array([[ 7, 10], [15, 22]])
array([0, 0])
- Getting the mean, variance and Standard Deviation
ip: numpy_array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) mean = numpy_array.mean() variance = numpy_array.var() standard_deviation = numpy_array.std() print('Mean :',mean) print('Variance:',variance) print('Standard Deviation:', standard_deviation)op: Mean : 5.0
Variance: 6.666666666666667
Standard Deviation: 2.581988897471611