栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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])
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/589260.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号