Reshaping and stacking
reshape
Python
import numpy as np
a = np.arange(1, 13) # 12 numbers in a row
print(a.reshape(3, 4)) # 3 rows of 4
print(a.reshape(2, 6))
print(a.reshape(2, 2, 3)) # 2 blocks of 2 rows by 3 columnsreshape arranges the same elements into a new shape, filling row by row. The total must stay the same: 12 elements can be 3 × 4 or 2 × 6, but not 5 × 3, which raises an error.
Let NumPy work out one dimension: -1
Python
import numpy as np
a = np.arange(12)
print(a.reshape(4, -1).shape) # (4, 3): -1 means "whatever fits"
print(a.reshape(-1, 6).shape) # (2, 6)
print(a.reshape(-1).shape) # (12,): back to one dimensionFlattening
Python
import numpy as np
grid = np.array([[1, 2, 3],
[4, 5, 6]])
print(grid.flatten()) # a 1D copy
print(grid.ravel()) # a 1D view where possible (no copy)Transposing
Python
import numpy as np
m = np.array([[1, 2, 3],
[4, 5, 6]])
print(m.T) # rows become columns
print(m.shape, "->", m.T.shape).T swaps the axes: a 2 × 3 array becomes 3 × 2. It returns a view, so it costs nothing to compute.
Adding an axis
Python
import numpy as np
v = np.array([1, 2, 3])
print(v.shape) # (3,)
print(v[np.newaxis, :].shape) # (1, 3): a row
print(v[:, np.newaxis].shape) # (3, 1): a column
print(v.reshape(-1, 1)) # the same column, using reshapeA 1D array is neither a row nor a column. Adding an axis makes it one or the other, which matters for broadcasting, the next lesson.
Joining arrays
Python
import numpy as np
a = np.array([[1, 2],
[3, 4]])
b = np.array([[5, 6],
[7, 8]])
print(np.concatenate([a, b])) # stacked vertically (axis 0)
print(np.concatenate([a, b], axis=1)) # side by side (axis 1)
print(np.vstack([a, b]).shape) # (4, 2): the same as axis 0
print(np.hstack([a, b]).shape) # (2, 4): the same as axis 1The arrays must match along every axis except the one you join on.
Splitting arrays
Python
import numpy as np
a = np.arange(12)
first, second, third = np.split(a, 3) # three equal parts
print(first, second, third)
m = np.arange(16).reshape(4, 4)
top, bottom = np.split(m, 2) # split the rows in half
left, right = np.split(m, 2, axis=1) # split the columns in half
print(top)
print(right)Finished this lesson?Mark it complete to earn +20 XP and move your progress on.