python当中不规则的list类型数据转为numpy格式

python当中不规则的list类型数据转为numpy格式,第1张

python当中不规则的list类型数据转为numpy格式

在前段时间写代码的时候,遇到一个bug:

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

问题分析

造成该错误的原因是:试图将一个不规则的list类型的数据使用numpy.array()函数转换为numpy格式。当我们对一个具有规则格式的list进行numpy格式转换时:

regular_list = [[1, 2, 3, 4], [1, 1, 0, 0], [1, 2, 1, 1]]	# 一个shape为(3, 4)的规则list
regular_np = numpy.array(regular_list)	# 完成转换

>> regular_np 
array([[1, 2, 3, 4],
       [1, 1, 0, 0],
       [1, 2, 1, 1]])

但是如果list数据的形状不规则的话,进行上述代码的转换就会出现bug,如下代码所示:

irregular_list = [[1, 2, 3, 4], [1, 1, 0, 0], [1, 2]]	# 不规则的list
irregular_np = numpy.array(irregular_list)		# 同样的方式转换

>> irregular_np
array([list([1, 2, 3, 4]), list([1, 1, 0, 0]), list([1, 2])], dtype=object)
解决办法

可以使用numpy.concatenate()函数进行转换,该函数会将list的数据转为numpy格式,并且进行展平,如下代码所示:

irregular_list = [[1, 2, 3, 4], [1, 1, 0, 0], [1, 2]]	# 不规则的list
irregular_np = numpy.concatenate(irregular_list)

>> irregular_np
array([1, 2, 3, 4, 1, 1, 0, 0, 1, 2])

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5594648.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存