Write Python. Understand every error.

Starting Python in your browser…

NumPy · topic 23 of 25

Reshaping and combining

reshape gives the same values a new shape, reading them row by row. The total number of elements must not change: 12 values can become (3, 4), (2, 6) or (12, 1), but not (5, 3). Put -1 in one position to let NumPy work out that size.

a = np.arange(12)
print(a.reshape(3, 4))
print(a.reshape(2, -1).shape)   # (2, 6)

flatten() turns any array back into one dimension. The attribute .T gives the transpose, swapping rows and columns, so a (2, 3) array becomes (3, 2).

To join arrays:

  • np.concatenate([a, b]) joins along an existing axis, rows by default; add axis=1 to join side by side
  • np.vstack([a, b]) stacks vertically, one on top of the other
  • np.hstack([a, b]) stacks horizontally, side by side

The sizes along every other dimension must match. Stacking a 3-column array on top of a 4-column array fails.

Key takeaways

  • reshape rearranges the same elements into a new shape, and the total number of elements must stay the same.
  • .T swaps rows and columns, and flatten() makes a single row.
  • np.concatenate, np.vstack and np.hstack join arrays end to end, one above the other, or side by side.
  • Arrays that are joined must have matching sizes along the other dimension.

Common mistakes

  • Reshaping to a shape with a different number of elements, such as 6 elements into (4, 2). Read the ValueError guide.
  • Stacking arrays whose other dimension does not match. Read the ValueError guide.
  • Confusing vstack (one on top of the other) with hstack (side by side).

Share this page:

Ctrl + Enter to run
Line 1, column 1Tab indents 4 spaces. Press Esc then Tab to leave the editor.