I experienced some unexpected behavior of np.save()
.
Assume, you want to save two numpy arrays into one .npy
file (as an object). As long both arrays have the same shape this works without any problem, but when the leading dimension is the same an error occurs.
The problem is caused by np.asanyarray()
, which is called in np.save()
prior saving.
It is clear that one could solve this problem by e.g. saving into different files, but I am not looking for another solution, I want to understand this behavior of np.save()
.
Here is the code:
import numpy as np
a = np.zeros((10, 5))
b = np.zeros((10, 2))
np.save('test', [a, b])
Causes this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/python3/lib/python3.6/site-packages/numpy/lib/npyio.py", line 509, in save
arr = np.asanyarray(arr)
File "/python3/lib/python3.6/site-packages/numpy/core/numeric.py", line 544, in asanyarray
return array(a, dtype, copy=False, order=order, subok=True)
ValueError: could not broadcast input array from shape (10,5) into shape (10)
When the leading dimension is different there is no problem:
a = np.zeros((9, 5))
b = np.zeros((10, 2))
np.save('test', [a, b])
For me this behavior of np.save
is inconsistent and seems to be a bug.