NumPy Reshaping & Combining Arrays
Last Updated: 09 Nov 2025
Reshaping means changing the shape or dimensions of an array without changing its data. We often reshape arrays before feeding them into ML models or matrix operations.
Hinglish Tip: “Reshape ka matlab hota hai — same data, bas arrangement change karna.”
np.reshape()
- Total elements must match: new shape = old size.
- Use
-1for one unknown dimension only.
import numpy as np
arr = np.arange(12)
print(arr)
print("Shape:", arr.shape)
reshaped = arr.reshape(3, 4)
print(reshaped)
print("Reshaped Shape:", reshaped.shape)
# Unknown dimension
reshaped = arr.reshape(3, -1) # -1 → auto-calculate
print(reshaped)
print("Reshaped Shape:", reshaped.shape)
Flattening Arrays
np.ravel() → View (changes affect original)
arr = np.array([[1, 2], [3, 4]])
flat = arr.ravel()
print(flat)
flat[0] = 99
print(arr) # original changed!
np.flatten() → Copy (original safe)
arr = np.array([[1, 2], [3, 4]])
flat = arr.flatten()
flat[0] = 99
print(arr) # original NOT changed
np.ravel()=reshape(-1)→ faster, memory-efficient
Transpose → .T
arr = np.array([[1, 2, 3],
[4, 5, 6]])
transposed = arr.T
print(transposed)
# [[1 4]
# [2 5]
# [3 6]]
Hinglish Tip: “Transpose = rows ban jate hain columns, columns ban jate hain rows.”
Stacking Arrays
np.concatenate() — along existing axis
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6]])
print(np.concatenate((a, b), axis=0)) # vertical
np.vstack() — Vertical stack
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.vstack((a, b)))
# [[1 2 3]
# [4 5 6]]
np.hstack() — Horizontal stack
print(np.hstack((a, b))) # [1 2 3 4 5 6]
np.dstack() — Depth (3rd axis)
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
print(np.dstack((a, b)))
# [[[1 5]
# [2 6]]
#
# [[3 7]
# [4 8]]]
Splitting Arrays
np.split() — into N equal parts
arr = np.arange(10)
print(np.split(arr, 2)) # 2 parts → [[0..4], [5..9]]
np.hsplit() — split columns
arr = np.arange(16).reshape(4, 4)
print(np.hsplit(arr, 2)) # two 4×2 arrays
np.vsplit() — split rows
print(np.vsplit(arr, 2)) # two 2×4 arrays
Use Cases
# Prepare image batch: 100 images → (100, 28, 28) to (100, 784)
images = np.random.rand(100, 28, 28)
flattened = images.reshape(100, -1) # ML model input
print(flattened.shape) # (100, 784)