在使用np.asarray()或np.asanyarray()时报这个错,是因为要array化的对象“在第一维后具有不均匀的形状”,比如下面这样:
import numpy as np
li = [[1, 2], [3, 4, 5]]
arr = np.asarray(li)
# ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part.
有的numpy版本不报错而是警告:
VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
根据提示,加上 dtype=object 就不会再报错或警告:
import numpy as np
li = [[1, 2], [3, 4, 5]]
arr = np.asarray(li, dtype=object) # [list([1, 2]) list([3, 4, 5])]
解决。(如果本意需要转换的是均匀数据,就找找数据的问题)
我是在np.save()时遇到的这个情况,np.save()需要传入arr : array_like,我传入的是如上一个第一维后不均匀的list,在np.save()内部有arr = np.asanyarray(arr),为了不改变内置函数,可以选择在外部将list转为np.ndarray,再传入该np.ndarray,比如:
import numpy as np
path = './mydata.txt'
li = [[1, 2], [3, 4, 5]]
# np.save(path, li)
arr = np.asarray(li, dtype = object)
np.save(path, arr)