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
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]]
Above concept is called Broadcasting. We will learn more about it later.
Hinglish Tip: “Broadcasting ka matlab hai chhote array ko bada bana ke match kar dena — bina actual copy banaye!”
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
print(np.mod(a, 2)) # Modulo
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)
array_equal()
- Two arrays 100% identical in shape AND every single number.
equal_nan=Truetreat NaN as equal
import numpy as np
a = np.array([1, 2, 3])
b = np.array([1, 2, 3])
c = np.array([1, 2, 4])
d = np.array([1, 2, 3, 4])
print(np.array_equal(a, b)) # True ← perfect match
print(np.array_equal(a, c)) # False ← one number different
print(np.array_equal(a, d)) # False ← different length
Insertion and Appending
insert()method adds an element to an array at a specified index.append()method adds an element to the end of an array.
arr = np.array([1, 2, 3])
print(arr)
arr.insert(1, 99)
print(arr)
# [1 99 2 3]
arr.append(100)
print(arr)
# [1 99 2 3 100]
Type Casting
astype()method changes the data type of an array.dtypeattribute returns the data type of an array.dtype.namereturns the name of the data type.
arr = np.array([1, 2, 3])
print(arr.dtype)
arr = arr.astype(np.float64)
print(arr.dtype)