Numpy_Notes (1)
Numpy_Notes (1)
Introduction to NumPy
NumPy (Numerical Python) is a Python library used for numerical computa-
tions. It provides support for arrays, matrices, and a collection of mathematical
functions to operate on these data structures.
Key Features
1. N-dimensional array objects: Provides multi-dimensional arrays called
ndarray.
2. Broadcasting: Enables operations on arrays of different shapes.
Getting Started
import numpy as np
Create Arrays
1. 1D Array:
2. 2D Array:
1
zeros = np.zeros((2, 3)) # 2x3 array of zeros
ones = np.ones((3, 2)) # 3x2 array of ones
4. Empty Array:
5. Range of Numbers:
Array Properties
• arr.shape: Shape of the array.
• arr.ndim: Number of dimensions.
• arr.size: Total number of elements.
• arr.dtype: Data type of elements.
• arr.itemsize: Memory size of one element.
Array Manipulation
1. Reshape:
reshaped = arr.reshape(2, 3)
2. Flatten:
flat = arr.ravel()
3. Transpose:
transposed = arr.T
2
4. Concatenate:
5. Stacking:
• Vertical: np.vstack((arr1, arr2))
• Horizontal: np.hstack((arr1, arr2))
2. Slicing:
3. Boolean Indexing:
4. Fancy Indexing:
Mathematical Operations
1. Element-wise Operations:
2. Matrix Multiplication:
3
3. Statistical Functions:
mean = np.mean(arr)
std_dev = np.std(arr)
min_val = np.min(arr)
max_val = np.max(arr)
4. Aggregates:
sum_all = np.sum(arr)
sum_axis0 = np.sum(arr, axis=0)
sum_axis1 = np.sum(arr, axis=1)
3. Inverse of a Matrix:
inv_matrix = np.linalg.inv(matrix)
2. Random Floats:
random_floats = np.random.rand(3, 2)
np.random.seed(42)
4
Applications of NumPy
1. Data Preprocessing: Used for cleaning, transforming, and preparing
data.
2. Machine Learning: Works with datasets, matrices, and mathematical
operations.
3. Image Processing: Handles pixel data efficiently.