ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape

在使用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)

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值