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
vstackandhstackare the readable cases ofconcatenate.stackadds a new axis;concatenateuses an existing one.splitreturns a list of views.
Keywords and builtins used here
asforprint
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.
Step 3 of 4 in Types & shapes, step 11 of 22 in NumPy.