NumPy Array Operations
How to work with arrays in NumPy.
NumPy provides powerful operations to manipulate arrays efficiently. Here are the key operations:
Arithmetic Operations
NumPy allows element-wise arithmetic operations.
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
# Addition
print(arr1 + arr2) # [5 7 9]
# Subtraction
print(arr1 - arr2) # [-3 -3 -3]
# Multiplication
print(arr1 * arr2) # [4 10 18]
# Division
print(arr1 / arr2) # [0.25 0.4 0.5 ]
# Exponentiation
print(arr1 ** 2) # [1 4 9]
Broadcasting
Element-wise Operations on Different Shapes. Broadcasting allows NumPy to perform operations on arrays of different shapes.
arr = np.array([[1, 2, 3], [4, 5, 6]])
scalar = 2
print(arr * scalar)
Output:
[[ 2 4 6]
[ 8 10 12]]
Aggregation Functions
Aggregation functions operate on arrays and return a single value. Ex. Sum, Mean, Min, Max, etc.
arr = np.array([1, 2, 3, 4, 5])
print(arr.sum()) # 15
print(arr.mean()) # 3.0
print(arr.min()) # 1
print(arr.max()) # 5
print(arr.std()) # Standard Deviation
print(arr.prod()) # Product of all elements
Matrix Operations
NumPy supports linear algebra operations like dot products and transposition.
- Matrix multiplication (Dot Product)
mat1 = np.array([[1, 2], [3, 4]])
mat2 = np.array([[5, 6], [7, 8]])
print(np.dot(mat1, mat2))
Output:
[[19 22]
[43 50]]
- Transpose of a matrix
print(mat1.T)
Output:
[[1 3]
[2 4]]
Logical Operations
You can compare elements using logical operators.
arr = np.array([10, 20, 30, 40])
print(arr > 20) # [False False True True]
print(arr == 10) # [ True False False False]
# Filtering elements using conditions
print(arr[arr > 20]) # [30 40]
Stacking & Concatenation
You can join arrays vertically or horizontally.
- Vertical Stack
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
print(np.vstack((arr1, arr2)))
Output:
[[1 2 3]
[4 5 6]]
- Horizontal Stack
print(np.hstack((arr1, arr2)))
Output:
[1 2 3 4 5 6]
No questions available.