2011-12-16 35 views
5

我试图检索一个recarray的列标题,并且遇到相当大的麻烦。如果我使用pylab的csv2rec功能在.csv文件中读取,我可以访问下列方式列标题:获取重新数组属性/列python

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

在哪里“列1”是第一列的标题,它会返回休息列中的值。但是,我正在阅读一个.csv文件,我不知道列标题的所有值是什么,我希望能够访问它们(循环或设置列表)。这看起来应该很简单。有任何想法吗?

回答

7

您可以使用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') 

或者,使用例如:

[[email protected] ~/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