NumPy Complete Notes with Examples
What is NumPy?
NumPy (Numerical Python) is a powerful Python library for numerical computations. It provides support for
arrays, matrices, and many mathematical functions.
Installation
Install using pip:
pip install numpy
Importing NumPy
The convention is:
import numpy as np
Creating Arrays
1D Array: np.array([1, 2, 3])
2D Array: np.array([[1, 2], [3, 4]])
Zeros: np.zeros((2,3))
Ones: np.ones((2,3))
Arange: np.arange(0, 10, 2)
Linspace: np.linspace(0, 1, 5)
Array Attributes
- shape: array.shape
- size: array.size
- ndim: array.ndim
- dtype: array.dtype
Indexing and Slicing
Access: arr[1], arr[1:3], arr[:, 0]
Negative Index: arr[-1]
NumPy Complete Notes with Examples
Boolean Indexing: arr[arr > 5]
Array Operations
Element-wise operations:
- Addition: arr1 + arr2
- Multiplication: arr1 * arr2
Matrix multiplication: np.dot(arr1, arr2)
Mathematical Functions
Common functions:
- np.sum(), np.mean(), np.std(), np.min(), np.max()
- np.sqrt(), np.exp(), np.log(), np.sin()
Reshaping Arrays
Use reshape(): arr.reshape(2, 3)
Flatten: arr.flatten()
Useful NumPy Functions
- np.unique()
- np.concatenate()
- np.split()
- np.sort()
- np.where(condition, x, y)
Random Module in NumPy
- np.random.rand(2, 2): uniform dist
- np.random.randn(2, 2): normal dist
- np.random.randint(0, 10, size=5)
- Set seed: np.random.seed(42)
NumPy Complete Notes with Examples
Example Program
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print("Shape:", arr.shape)
print("Sum:", np.sum(arr))
print("Mean:", np.mean(arr))