numpy:非结构化数组到结构化数组

时间:2020-07-16 07:04:26

标签: arrays numpy

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

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], 
....
]

我该如何实现?

1 个答案:

答案 0 :(得分:1)

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

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]