gpt4 book ai didi

python - 获取 recarray 属性/列 python

转载 作者:太空狗 更新时间:2023-10-29 21:38:05 25 4
gpt4 key购买 nike

我正在尝试检索 recarray 的列标题,但遇到了相当大的麻烦。如果我使用 pylab 的 csv2rec 函数读入 .csv 文件,我可以通过以下方式访问列标题:

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

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

最佳答案

你可以使用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

关于python - 获取 recarray 属性/列 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8530670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com