Labs ICT
Pro Login

Reshaping Arrays

Changing the shape without changing the data.

Reshaping Arrays

Reshaping is like rearranging furniture - same pieces, different layout. NumPy lets you change array shape without changing the data. Super useful for data preparation.

Basic Reshape

reshape() changes dimensions. The total elements must stay the same.


import numpy as np

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

print(f"Original: {arr}")
print(f"Reshaped to 2x3:\n{reshaped}")
    

6 elements can become 2x3, 3x2, or 6x1. But not 2x4 - that's 8 elements.

Using -1 for Auto-calculation

Let NumPy figure out one dimension with -1.


import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
print(f"2 rows: {arr.reshape(2, -1)}")
print(f"4 rows: {arr.reshape(-1, 4)}")
    

Here is the thing - -1 tells NumPy "calculate this dimension for me". It's a huge time saver.

Flatten vs Ravel

Both convert multi-dimensional arrays to 1D, but with a difference.


import numpy as np

matrix = np.array([[1, 2, 3], [4, 5, 6]])
flat = matrix.flatten()
raveled = matrix.ravel()

print(f"Original:\n{matrix}")
print(f"Flattened: {flat}")
print(f"Raveled: {raveled}")
    

flatten() returns a copy, ravel() returns a view (when possible). Use ravel for performance, flatten when you need a separate copy.

Newaxis

Add new dimensions with np.newaxis or None.


import numpy as np

arr = np.array([1, 2, 3])
print(f"Original shape: {arr.shape}")
print(f"With newaxis: {arr[np.newaxis, :].shape}")
    

One thing that confused me at first was when to use newaxis. It's often needed for broadcasting operations.

Try it Yourself →

Key Takeaways

  • reshape() changes dimensions without changing data
  • Use -1 to auto-calculate a dimension
  • flatten() returns copy, ravel() returns view
  • newaxis adds new dimensions for broadcasting