Skip to main content
Practice

Array Reshaping and Flattening

NumPy allows you to reshape arrays — adjusting rows and columns while keeping the same data.

You can also flatten multi-dimensional arrays into a single 1D sequence.


Reshaping

Use .reshape(rows, columns) to change the shape of an array.

The total number of elements must remain the same.

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

print(reshaped)
# [[1 2 3]
# [4 5 6]]

Flattening

Use .flatten() to convert any multi-dimensional array into a 1D array.

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

print(flat) # [1 2 3 4 5 6]

Summary

  • Use .reshape() to change an array's shape without changing its data
  • Use .flatten() to reduce any array to 1D

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.