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 -1 for 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.flatten() → Copy (original safe)

  • Returns a new 1D copy.
  • flatten() always creates a copy.
arr = np.array([[1, 2], [3, 4]])
flat = arr.flatten()
flat[0] = 99
print(arr)   # original NOT changed

np.ravel() → View (changes affect original)

  • Turn any array (2D, 3D, 10D…) into a flat 1D array.
  • Tries to give you a view (no copy) which is super fast and saves memory.
  • Use ravel() 99% of the time. Only use flatten() when you are scared of changing the original array by mistake.
arr = np.array([[1, 2], [3, 4]])
flat = arr.ravel()
print(flat)
flat[0] = 99
print(arr)   # original changed!

np.ravel() = reshape(-1) → faster, memory-efficient

Note You can check Whether an array is a view or copy using base attribute. if True, it is a view.


Transpose → .T

It transposes the array means swap rows and columns.

arr = np.array([[1, 2, 3],
                [4, 5, 6]])
transposed = arr.T
print(transposed)

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],[4,7]])
print(np.concatenate((a, b), axis=0))   # vertical
print(np.concatenate((a, b), axis=1))   # horizontal

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)))

Splitting Arrays

np.split() — into N equal parts

arr = np.arange(10)
print(np.split(arr, 2))   # 2 parts → [[0..4], [5..9]]

Passing axis=1 splits columns and axis=0 splits rows

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