shaare.it

ValueError: total size of new array must be unchanged

7 Dec 2025

1 min read

ValueError: total size of new array must be unchanged

$ python -c "import numpy as np; a=np.arange(6); a.reshape((4,2))"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ValueError: total size of new array must be unchanged

Why this happens

Reshape requires the product of the new dimensions equal the number of elements in the original array.

Fix

Pick dimensions that multiply to the original size or use -1 to infer one dimension.

Wrong code

import numpy as np
a = np.arange(6)
print(a.reshape((4,2)))

Fixed code

import numpy as np
a = np.arange(6)
print(a.reshape((3,2)))

# or infer dimension
print(a.reshape((2,-1)))