reshape and -1
import numpy as np a = np.arange(1, 13) print(a.reshape(3, 4)) print(a.reshape(4, -1)) print(a.reshape(-1, 6).shape)
Write Python. Understand every error.
NumPy · topic 23 of 25
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 sidenp.vstack([a, b]) stacks vertically, one on top of the othernp.hstack([a, b]) stacks horizontally, side by sideThe sizes along every other dimension must match. Stacking a 3-column array on top of a 4-column array fails.
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.vstack (one on top of the other) with hstack (side by side).
import numpy as np a = np.arange(1, 13) print(a.reshape(3, 4)) print(a.reshape(4, -1)) print(a.reshape(-1, 6).shape)
import numpy as np m = np.array([[1, 2, 3], [4, 5, 6]]) print(m.T) print(m.T.shape) print(m.flatten())
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]))
import numpy as np x = np.array([[1, 2], [3, 4]]) y = np.array([[5, 6], [7, 8]]) print(np.concatenate([x, y])) print(np.concatenate([x, y], axis=1))
5 quick questions to check your understanding. Choose an answer for each, then press Check answers.
import numpy as np print(np.arange(6).reshape(3, 2).shape)
reshape(3, 2) arranges 6 values into 3 rows and 2 columns.
import numpy as np a = np.array([[1, 2, 3], [4, 5, 6]]) print(a.T.shape)
.T (transpose) swaps rows and columns.
import numpy as np a = np.array([[1, 2], [3, 4]]) print(a.flatten())
flatten turns any array into one flat row.
import numpy as np a = np.array([1, 2]) b = np.array([3, 4]) print(np.concatenate([a, b]))
concatenate joins arrays end to end.
The total number of elements must stay the same.