Python Numpy
Python Numpy
NumPy is an open-source Python library that is used to work with arrays and perform mathematical
operations. NumPy stands for Numerical Python. NumPy is widely used in Data Science and Machine
Learning.
NumPy is very useful for developers as it has functions in the field of matrices, random number
generation, linear algebra, Fourier Transform, Mathematical and logical operations on arrays.
NumPy’s data structure and the key concept is n-dimensional arrays (ndarray). These arrays can have
one or more dimensions, or they can be 0-dimensional.
1. Scalar (0D)
2. Vector (1D)
3. Matrix (2D)
4. Tensor (>=3D)
Benefits of NumPy
● Fast:NumPy is written in C (and also C++ and Fortran) programming language, consequently it
is much faster than Python Lists.
● Memory Usage:NumPy arrays are fixed length, on the other hand Python Lists can be expanded
in size. NumPy uses less memory and storage space.
2. Importing NumPy
import numpy as np
3. Creating Arrays
1D Array:
3D Array:
arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
4. Array Attributes
Shape: Returns the dimensions of the array.
arr.shape
5. Array Initialization
Zeros:
np.zeros((3, 3)) # 3x3 matrix of zeros
Ones:
np.ones((2, 2)) # 2x2 matrix of ones
Identity Matrix:
np.eye(3) # 3x3 identity matrix
Random:
np.random.rand(2, 2) # 2x2 matrix with random values
6. Reshaping Arrays
You can change the shape of an array without modifying its data.
arr = np.array([1, 2, 3, 4, 5, 6])
arr_reshaped = arr.reshape((2, 3)) # Reshape to 2x3 matrix
8. Array Operations
Element-wise addition:
arr1 + arr2
Element-wise multiplication:
arr1 * arr2
Dot product:
np.dot(arr1, arr2)
9. Broadcasting
Smaller arrays are “broadcast” to match the shape of larger arrays during operations.
np.sum(arr)
Mean:
np.mean(arr)
Standard deviation:
np.std(arr)
Maximum & Minimum:
np.max(arr), np.min(arr)
Concatenation:
np.save('my_array', arr)
Load from file:
arr = np.load('my_array.npy')