NumPy II

Array Reshaping

Learn how to change the shape of a NumPy array using reshape() and convert it back to 1D with flatten().


reshape() lets you change an array's dimensions without changing its data — as long as the total number of elements stays the same.

Turn a 1D array of 6 elements into a 2×3 matrix:

Python
Output

What will be the output?

Python

Pass -1 for one dimension and NumPy calculates it automatically:

Python
Output

What will be the output?

Python

flatten() converts any array back to 1D, row by row:

Python
Output

What will be the output?

Python

Combining np.arange() with reshape() is a common pattern for creating structured arrays:

Python
Output

What will be the output?

Python

What will be the output?

Python