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:
arr = np.array([1, 2, 3])
2D Array:
arr = np.array([[1, 2, 3], [4, 5, 6]])
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
Size: Total number of elements in the array.
arr.size
Data Type: Type of elements in the array.
arr.dtype
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
7. Array Indexing & Slicing
Access specific elements by index.
arr[0, 1] # Row 0, Column 1
Slice arrays to extract subarrays.
arr[0:2, 1:3] # Rows 0-1, Columns 1-2
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.
arr + 5 # Adds 5 to every element of the array
10. Mathematical Functions
Sum:
np.sum(arr)
Mean:
np.mean(arr)
Standard deviation:
np.std(arr)
Maximum & Minimum:
np.max(arr), np.min(arr)
11. Array Concatenation & Splitting
Concatenation:
np.concatenate((arr1, arr2), axis=0) # Concatenate along rows
Splitting:
np.split(arr, 2) # Split into 2 equal subarrays
12. Logical Operations
Element-wise comparison returns a boolean array.
arr > 2 # Returns True where elements are greater than 2
Any and All for boolean arrays:
np.any(arr > 2) # Returns True if any element is greater than 2
np.all(arr > 2) # Returns True if all elements are greater than 2
13. Array Copying
Shallow Copy: Creates a new array that references the original data.
arr_copy = arr.view()
Deep Copy: Creates a new array and copies the data.
arr_copy = arr.copy()
14. Saving and Loading Arrays
Save to file:
np.save('my_array', arr)
Load from file:
arr = np.load('my_array.npy')