reshape only reorganizes how the same elements are grouped into dimensions — the total element count must stay exactly the same, so a 12-element array can become (3, 4), (4, 3), (2, 6), or (2, 2, 3), but never (3, 5). Passing -1 for one dimension tells NumPy to calculate that dimension automatically from the array's total size and the other specified dimensions, which is convenient when you know some dimensions but not all of them.
1Understanding np.reshape()
reshape only reorganizes how the same elements are grouped into dimensions — the total element count must stay exactly the same, so a 12-element array can become (3, 4), (4, 3), (2, 6), or (2, 2, 3), but never (3, 5). Passing -1 for one dimension tells NumPy to calculate that dimension automatically from the array's total size and the other specified dimensions, which is convenient when you know some dimensions but not all of them.
Use -1 for one dimension in reshape(), e.g. arr.reshape(-1, 1) to make a column vector, instead of computing that dimension yourself — it's less error-prone and adapts automatically if the array's size changes.
import numpy as np
arr = np.arange(12)
reshaped = arr.reshape(3, 4)
print(reshaped)2Practical Example
Here is a real-world application of np.reshape() showing how it is used in production NumPy code.
import numpy as np
arr = np.arange(6)
column = arr.reshape(-1, 1)
print(column)3Best Practices
Follow these guidelines when working with np.reshape():
1. Use -1 for exactly one dimension in reshape() to let NumPy infer it, instead of computing and hardcoding that value yourself
2. Remember reshape() returns a view when possible, so mutating the reshaped array can also mutate the original — call .copy() if you need independence
3. Check the total element count matches before reshaping, or catch the resulting ValueError, rather than assuming a reshape will always succeed
Tip: Use -1 for one dimension in reshape(), e.g. arr.reshape(-1, 1) to make a column vector, instead of computing that dimension yourself — it's less error-prone and adapts automatically if the array's size changes.
import numpy as np
arr = np.arange(12)
reshaped = arr.reshape(3, 4)
print(reshaped)