typestar

Stacking and splitting in Python

Joining arrays along a new or existing axis, and cutting them back up.

import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

print(np.vstack([a, b]))
print(np.hstack([a, b]))
print(np.stack([a, b], axis=1))
print(np.concatenate([a, b]).shape, np.stack([a, b]).shape)
print([part.tolist() for part in np.split(np.arange(6), 3)])

How it works

  1. vstack and hstack are the readable cases of concatenate.
  2. stack adds a new axis; concatenate uses an existing one.
  3. split returns a list of views.

Keywords and builtins used here

The run, in numbers

Lines
10
Characters to type
271
Tokens
129
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 74 seconds.

Type this snippet

Step 3 of 4 in Types & shapes, step 11 of 22 in NumPy.

← Previous Next →