Reshape, transpose, and combine arrays
2.5.5
Change how existing values are arranged and distinguish joining an axis from adding one.
On this page
Reshape or transpose
reshape keeps the element count fixed and can infer one axis set to -1. T transposes a 2D array. A reshape can return a view or a copy depending on the memory layout.
import numpy as np
a = np.arange(1, 7).reshape(2, -1)
print(a.tolist())
print(a.T.shape)
Example output
[[1, 2, 3], [4, 5, 6]] (3, 2)
Concatenate or stack
concatenate joins arrays along an existing axis. stack adds a new axis. For stack, all input arrays must have the same shape.
import numpy as np
a, b = np.array([1, 2]), np.array([3, 4])
print(np.concatenate([a, b]).shape)
print(np.stack([a, b]).shape)
Example output
(4,) (2, 2)