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

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

Example:



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

You may also like...