重组元组数组 [英] Restructuring Array of Tuples

查看:90
本文介绍了重组元组数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个元组数组,其中第二级不应该是元组,我想将其全部转换为二维数组. 有没有一种快速的方法可以将这个凌乱的1-d重组为一个干净的2-d或结构化数组?

I have an array of tuples of tuples where the second level should not be a tuple and I want to convert it all to something like a 2-d array. Is there a quick way to restructure from this messy 1-d to a nice clean 2-d or structured array?

注意:这些元组包含各种类型.我希望能够转置和二维切片等.此数据.

Note: These tuples do contain various types. I would like to be able to transpose and 2-d slice etc.. this data.

即...

[((1,-4,7.0),)
((2,-5,8.0),)
((3,-6,9.0),)]

经过编辑以尝试解决人们对原始问题指出的问题

推荐答案

dtype在这里很重要.我能最接近您的显示器的是嵌套的dtype

The dtype is important here. The closest I can come to your display is with a nested dtype

In [182]: dt1=np.dtype('i,i,f')
In [183]: dt=np.dtype([('a',dt1,),('b',dt1,),('c',dt1,)])

In [184]: x=np.ones(1,dtype=dt)

In [185]: print(x)
[((1, 1, 1.0), (1, 1, 1.0), (1, 1, 1.0))]

(没有最终的,)

如果我使用repr而不是打印的默认str,我也会看到dtype:

If I use the repr rather than print's default str, I see the dtype as well:

In [186]: print(repr(x))
array([((1, 1, 1.0), (1, 1, 1.0), (1, 1, 1.0))], 
      dtype=[('a', [('f0', '<i4'), ('f1', '<i4'), ('f2', '<f4')]), ('b', [('f0', '<i4'), ('f1', '<i4'), ('f2', '<f4')]), ('c', [('f0', '<i4'), ('f1', '<i4'), ('f2', '<f4')])])

重塑或挤压在这里不起作用,因为它已经是1d. viewastype可以工作.您是否只想平整dtype或使其全部浮动?您期望什么样的形状?当前,每条记录由9个数字组成.

Reshape or squeeze does not work here because it is already 1d. view or astype can work. Do you want to just flatten the dtype, or make it all float? What kind of shape do you expect? Currently each record consists of 9 numbers.

使用兼容的dtype,我可以将该数组视为9个值的记录:

With a compatible dtype I can view this array as a record of 9 values:

In [195]: dt2=np.dtype('i,i,f,i,i,f,i,i,f')
In [196]: x.view(dt2)
Out[196]: 
array([(1, 1, 1.0, 1, 1, 1.0, 1, 1, 1.0)], 
      dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<f4'), ('f3', '<i4'), ('f4', '<i4'), ('f5', '<f4'), ('f6', '<i4'), ('f7', '<i4'), ('f8', '<f4')])

将此x转换为浮点数数组的最简单方法是使用tolist(不是最快):

The simplest way to turn this x into an array of floats is with tolist (it's not fastest):

In [256]: x['c']=(20,21,22)
In [257]: x['b']=(10,11,12)
In [258]: x['a']=(1,2,3)

In [263]: print(x)
[((1, 2, 3.0), (10, 11, 12.0), (20, 21, 22.0))]
In [264]: np.array(x.tolist())
Out[264]: 
array([[[  1.,   2.,   3.],
        [ 10.,  11.,  12.],
        [ 20.,  21.,  22.]]])

这篇关于重组元组数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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