NumPy Array Reshaping

1. Using reshape()

You can convert a 1D array into 2D, 3D, etc.

Example: Convert 1D → 2D

import numpy as np

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

Output:

[[1 2 3]
[4 5 6]]


2. Reshape to 3 Dimensions

arr = np.array([1,2,3,4,5,6,7,8])
newarr = arr.reshape(2,2,2)
print(newarr)

Output:

[[[1 2]
[3 4]]

[[5 6]
[7 8]]
]


⚠️ Important Rule: Total Elements Must Match

If the total number of items doesn’t match, reshape will give an error.

np.array([1,2,3]).reshape(2,2)

Error (because 3 elements cannot be reshaped into a 4-element structure).


3. Using -1 (Auto Calculate Dimension)

NumPy can automatically calculate missing dimension using -1.

Example:

arr = np.array([1,2,3,4,5,6])
newarr = arr.reshape(3, -1)
print(newarr)

Output:

[[1 2]
[3 4]
[5 6]]


4. Flatten an Array (reshape(-1))

Convert multi-dimensional array back to 1D.

arr = np.array([[1,2,3],[4,5,6]])
flat = arr.reshape(-1)
print(flat)

Output:

[1 2 3 4 5 6]

5. Check If Reshape Returns a View or Copy

arr = np.array([1,2,3,4,5,6])
reshaped = arr.reshape(2,3)

print(reshaped.base is arr) # Check if it's a view

If output is True, reshaping created a view, not a new copy.


Summary Table

Operation Function Changes Data? Changes Shape?
Flatten array .reshape(-1) ❌ No ✔ Yes
1D → 2D .reshape(r, c) ❌ No ✔ Yes
Auto dimension .reshape(-1) ❌ No ✔ Yes
View or Copy? .reshape() Sometimes ✔ Yes

🎯 Practical Example

arr = np.arange(1,13)
reshaped_arr = arr.reshape(3,4)
print(arr)
print(reshaped_arr)

Output:

[ 1 2 3 4 5 6 7 8 9 10 11 12]

[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *