获取recarray属性/列 python

10 投票
1 回答
8321 浏览
提问于 2025-04-17 08:29

我正在尝试获取一个记录数组(recarray)的列标题,但遇到了不少麻烦。如果我使用pylab的csv2rec函数读取一个.csv文件,我可以用以下方式访问列标题:

from pylab import csv2rec
x = csv2rec(file.csv)
x.column1
x.column2

这里的'column1'是第一列的标题,这样可以返回这一列的其他值。但是,我现在读取的这个.csv文件里,我不知道所有列标题的具体值,我想能够访问这些标题(要么循环遍历,要么设置一个列表)。这看起来应该很简单。有没有什么好主意?

1 个回答

16

你可以使用 x.dtype.names 来查看数据的名称:

>>> import numpy as np

>>> a = np.array([0.1,0.2])
>>> b = np.array([0.3,0.4])
>>> dtype = {'names' : ['a','b'], 'formats' : ['f8', 'f8']}
>>> c = np.rec.fromarrays([a,b], dtype = dtype)
>>> c
rec.array([(0.1, 0.3), (0.2, 0.4)], 
      dtype=[('a', '<f8'), ('b', '<f8')])
>>> print c.dtype.names
('a', 'b')

或者,按照你的例子来做:

[physics@aurora ~/calc ]$ cat csv.dat 
a,b
0.1,0.3
0.2,0.4

In [1]: from pylab import csv2rec

In [2]: x = csv2rec('csv.dat')

In [3]: for name in x.dtype.names:
   ...:         print name
a
b

撰写回答