numpy:非结构化数组到结构化数组 [英] numpy: unstructured array to structured array

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

问题描述

我想将非结构化数组转换为结构化数组.这是我的代码

I want to convert a unstructured array into structured array. Here is my code

import numpy as np
import numpy.lib.recfunctions as rf

data = np.arange(24).reshape(4,6)
dtype=[
    ("x", "f4"),
    ("y", "f4"),
    ("z", "f4"),
    ("red", "u1"),
    ("green", "u1"),
    ("blue", "u1"),
    ]
output_data = np.array(data, dtype=dtype)
print("output_data: ", output_data)                     

这是输出

output_data:  [[(  0.,   0.,   0.,  0,  0,  0) (  1.,   1.,   1.,  1,  1,  1)
  (  2.,   2.,   2.,  2,  2,  2) (  3.,   3.,   3.,  3,  3,  3)
  (  4.,   4.,   4.,  4,  4,  4) (  5.,   5.,   5.,  5,  5,  5)]
 [(  6.,   6.,   6.,  6,  6,  6) (  7.,   7.,   7.,  7,  7,  7)
  (  8.,   8.,   8.,  8,  8,  8) (  9.,   9.,   9.,  9,  9,  9)
  ( 10.,  10.,  10., 10, 10, 10) ( 11.,  11.,  11., 11, 11, 11)]
 [( 12.,  12.,  12., 12, 12, 12) ( 13.,  13.,  13., 13, 13, 13)
  ( 14.,  14.,  14., 14, 14, 14) ( 15.,  15.,  15., 15, 15, 15)
  ( 16.,  16.,  16., 16, 16, 16) ( 17.,  17.,  17., 17, 17, 17)]
 [( 18.,  18.,  18., 18, 18, 18) ( 19.,  19.,  19., 19, 19, 19)
  ( 20.,  20.,  20., 20, 20, 20) ( 21.,  21.,  21., 21, 21, 21)
  ( 22.,  22.,  22., 22, 22, 22) ( 23.,  23.,  23., 23, 23, 23)]]

但是我除外的是

output_data: [
[0., 1., 2., 3, 4, 5], 
....
]

我该如何实现?

推荐答案

如果 rf 对您不起作用,请尝试执行此操作(如注释中所述,结构化数据是元组结构的数组):

If rf does not work for you try this (as mentioned in the comments, the structured data is an array of tuples structure):

output_data = np.array([tuple(i) for i in data], dtype=dtype)

输出:

print("output_data: ", output_data) 
output_data:  [( 0.,  1.,  2.,  3,  4,  5) ( 6.,  7.,  8.,  9, 10, 11)
 (12., 13., 14., 15, 16, 17) (18., 19., 20., 21, 22, 23)]

print(output_data['red'])
[ 3  9 15 21]

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

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