Skip to main content
Practice

Array Reshaping and Flattening

NumPy makes it easy to reshape arrays by changing the number of rows and columns without altering the data.

You can also flatten a multi-dimensional array into a 1D array.


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.