NumPy Array Shape

📐 NumPy — Array Shape

The shape of a NumPy array tells how many rows, columns, and dimensions the array has.

It is represented as a tuple:

(shape_of_dim1, shape_of_dim2, shape_of_dim3, ...)

✅ 1. Checking Shape of an Array

Use .shape attribute:

import numpy as np

arr = np.array([10, 20, 30, 40])
print(arr.shape)

Output:

(4,)

Meaning → 1D array with 4 elements.


✅ 2. Shape of a 2-D Array

arr2 = np.array([[1, 2, 3], [4, 5, 6]])
print(arr2.shape)

Output:

(2, 3)

Meaning → 2 rows × 3 columns.


✅ 3. Shape of a 3-D Array

arr3 = np.array([
[[1,2],[3,4]],
[[5,6],[7,8]]
])

print(arr3.shape)

Output:

(2, 2, 2)

Meaning → 2 blocks, each with 2 rows and 2 columns.


🔄 Changing Shape — reshape()

You can change array shape without changing data.

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

print(reshaped)
print(reshaped.shape)


⭐ Important Rule: Total elements must remain the SAME

❌ Invalid:

arr.reshape(4, 4) # Error if arr has only 6 elements

🤖 Auto Dimension — Use -1

NumPy automatically calculates the missing dimension if you use -1.

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

print(arr.reshape(2, -1)) # NumPy will compute columns automatically


🧱 Flattening an Array (Convert to 1-D)

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

print(flat)

Output:

[1 2 3 4 5 6]

📌 Reshape vs Resize

Feature reshape() resize()
Returns new array ✅ Yes ❌ Modifies original
Data preservation Yes if compatible May repeat or trim data

Example:

arr.resize(2, 3)

🧠 Summary Table

Operation Example
Get array shape arr.shape
Reshape array arr.reshape(2,3)
Auto reshape arr.reshape(2, -1)
Flatten array arr.reshape(-1)
Resize original array arr.resize(3,3)

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 *