将列表列表转换为具有多种数据类型的numpy数组 [英] Converting list of lists to numpy array with multiple data types

查看:122
本文介绍了将列表列表转换为具有多种数据类型的numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从文件中读取的列表列表.每个内部列表的长度为6个元素,并具有3个字符串和5个浮点数.如何将列表列表转换为numpy数组?谢谢!

I have a list of lists I've read from a file. Each of the inner lists is six elements in length, and has 3 strings and 5 floats. How do I convert this list of lists into a numpy array? Thanks!

推荐答案

您想要一个结构化的数组,该数组具有复合dtype:

You want a structured array, one that has a compound dtype:

列表示例列表:

In [4]: ll = [['one','two',1,1.23],['four','five',4,34.3],['six','seven',4,34.3]]

尝试创建一个常规数组,生成一个字符串数组:

trying to make a regular array, produces an array of strings:

In [5]: np.array(ll)
Out[5]: 
array([['one', 'two', '1', '1.23'],
       ['four', 'five', '4', '34.3'],
       ['six', 'seven', '4', '34.3']], 
       dtype='|S5')

但是如果我指定一个包含两个字符串,一个int和一个浮点数的dtype,则会得到一个一维结构化数组:

But if I specify a dtype that contains 2 strings, and int and a float, I get a 1d structured array:

In [8]: np.array([tuple(x) for x in ll],dtype='S5,S5,i,f')
Out[8]: 
array([('one', 'two', 1, 1.2300000190734863),
       ('four', 'five', 4, 34.29999923706055),
       ('six', 'seven', 4, 34.29999923706055)], 
      dtype=[('f0', 'S5'), ('f1', 'S5'), ('f2', '<i4'), ('f3', '<f4')])

请注意,我必须将内部列表转换为元组.这就是结构化数组获取其输入以及显示它的方式.它有助于将结构化的行"与常规(二维)数组的统一行"区分开来.

Note that I had to convert the inner lists to tuples. That's how a structured array takes its input, and also how it displays it. It helps distinguish the structured 'row' from the uniform 'row' of a regular (2d) array.

这与genfromtxtloadtxtcsv文件读取时生成的结构化数组相同.

This the same sort of structured array that genfromtxt or loadtxt produces when reading from a csv file.

还有其他指定dtype的方法,还有几种其他将数据加载到这样的数组中的方法.但这是一个开始.

There are other ways of specifying the dtype, and a couple of other ways of loading the data into such an array. But this is a start.

进一步的测试 https://stackoverflow.com/a/47774915/901925 显示此元组转换是不那么费时.简单地创建数组会花费更多时间.

Further testing, https://stackoverflow.com/a/47774915/901925, shows that this tuple conversion is not that time consuming. Simply creating the array takes more time.

这篇关于将列表列表转换为具有多种数据类型的numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆