Thuta Learning
AdvancedData & Databasesintermediate

Reshaping Arrays

Relax. We'll talk through this in plain words — no textbook voice.

reshape() changes an array's shape without changing the number of data elements. For example, you can turn a 1-D array with 9 elements into a 3x3 matrix. But if you try to reshape those same 9 elements into a 2x5, you'll get an error because that needs 10 slots.

python
import numpy as np

numbers = np.arange(1, 10)
print("Original:", numbers)
print("Original shape:", numbers.shape)

matrix = numbers.reshape((3, 3))
print("
3x3 matrix:
", matrix)

flattened = matrix.reshape(-1)
print("
Back to 1-D:", flattened)

np.arange(1, 10) produces 9 elements, from 1 to 9. reshape((3, 3)) turns that into 3 rows and 3 columns. reshape(-1) tells NumPy, "work out the size you need and flatten this back to 1-D yourself."

You should see
Original: [1 2 3 4 5 6 7 8 9] Original shape: (9,) 3x3 matrix: [[1 2 3] [4 5 6] [7 8 9]] Back to 1-D: [1 2 3 4 5 6 7 8 9]

Info

-1 should only be used in one spot in a reshape call. NumPy figures out the missing dimension from the rest.

Easy traps

  • The total number of slots in the shape you're reshaping to has to match the number of elements in the array. If they don't match, the reshape fails.

Exercise

Reshaping comes up constantly with image data and ML training data — think flattening image pixels into a vector, or turning row data back into a table format.

You'll know it worked when:

Reshaping Arrays | Thuta Learning