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:



 1. Checking Shape of an Array

Use .shape attribute:


 

Output:

(4,)

Meaning → 1D array with 4 elements.


 2. Shape of a 2-D Array


Output:

(2, 3)

Meaning → 2 rows × 3 columns.


 3. Shape of a 3-D Array


 

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.


 


⭐ Important Rule: Total elements must remain the SAME

❌ Invalid:



🤖 Auto Dimension — Use -1

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


 


🧱 Flattening an Array (Convert to 1-D)


 

Output:

[1 2 3 4 5 6]

📌 Reshape vs Resize

Featurereshape()resize()
Returns new array✅ Yes❌ Modifies original
Data preservationYes if compatibleMay repeat or trim data

Example:



🧠 Summary Table

OperationExample
Get array shapearr.shape
Reshape arrayarr.reshape(2,3)
Auto reshapearr.reshape(2, -1)
Flatten arrayarr.reshape(-1)
Resize original arrayarr.resize(3,3)

You may also like...