NumPy Array Operations
Last Updated: 09 Nov 2025
NumPy performs them element-wise and super fast (no loops needed).
Hinglish Tip: “NumPy me loop likhne ki zarurat nahi, operations ek saath poore array par apply ho jaate hain — isse code fast aur clean hota hai.”
Basic Arithmetic Operations
These operations happen element-wise — NumPy matches each position in both arrays.
import numpy as np
a = np.array([10, 20, 30, 40])
b = np.array([1, 2, 3, 4])
print(a + b) # Addition
print(a - b) # Subtraction
print(a * b) # Multiplication
print(a / b) # Division
print(a % b) # Modulus
print(a ** b) # Power
Built-in Universal Functions (ufuncs)
NumPy provides special mathematical functions called ufuncs that work on entire arrays.
import numpy as np
a = np.array([1, 2, 3, 4])
print(np.add(a, 5)) # Add scalar to array
print(np.subtract(a, 2)) # Subtract scalar
print(np.multiply(a, 3)) # Multiply by scalar
print(np.divide(a, 2)) # Divide by scalar
Comparison Operations
We can compare arrays directly — the result is a boolean array.
x = np.array([10, 20, 30])
y = np.array([20, 20, 10])
print(x == y)
print(x > y)
print(x <= y)
Broadcasting Concept
- Broadcasting lets NumPy operate on arrays of different shapes without copying data.
- The smaller array is stretched along the missing dimension.
Example 1 – scalar + array
arr = np.array([1, 2, 3])
print(arr + 10) # [11 12 13]
Example 2 – 2-D + 1-D
a = np.array([[1, 2, 3],
[4, 5, 6]])
b = np.array([10, 20, 30])
print(a + b)
# [[11 22 33]
# [14 25 36]]
Hinglish Tip: “Broadcasting ka matlab hai chhote array ko bada bana ke match kar dena — bina actual copy banaye!”
Filtering with Boolean Masks
Create a mask with a comparison, then use it to select elements.
data = np.array([12, 45, 67, 23, 89, 34, 91])
mask = data > 50
print("Mask:", mask) # [False False True False True False True]
print("Values > 50:", data[mask])
# [67 89 91]
# One-liner
print(data[data > 50])
Combine conditions
age = np.array([16, 22, 17, 65, 19])
mask = (age >= 18) & (age <= 60)
print("Eligible:", age[mask])
Warning: Use
&,|(notand,or) inside masks.
Modify in-place
data[data > 80] = 80 # cap values
print(data)