我可以重命名numpy记录数组中的字段

use*_*519 7 python numpy matplotlib

我是python的新手,所以这听起来很基本.我使用csv2rec导入了一个csv文件.第一行有标题.我想将标题更改为'x','y','z'.这样做的最佳方法是什么?

>>> import matplotlib
>>> import matplotlib.mlab as mlab
>>> r= mlab.csv2rec('HeightWeight.csv', delimiter= ',')
>>> names= r.dtype.names
>>> for i in names:
     print i


index
heightinches
weightpounds
Run Code Online (Sandbox Code Playgroud)

DSM*_*DSM 22

您可以简单地分配到.dtype.names:

>>> d = np.array([(1.0, 2), (3.0, 4)], dtype=[('a', float), ('b', int)])
>>> d
array([(1.0, 2), (3.0, 4)], 
      dtype=[('a', '<f8'), ('b', '<i8')])
>>> d['a']
array([ 1.,  3.])
>>> d.dtype.names
('a', 'b')
>>> d.dtype.names = 'x', 'y'
>>> d
array([(1.0, 2), (3.0, 4)], 
      dtype=[('x', '<f8'), ('y', '<i8')])
>>> d['x']
array([ 1.,  3.])
Run Code Online (Sandbox Code Playgroud)

同样的方式recarray:

>>> d
rec.array([(1.0, 2), (3.0, 4)], 
      dtype=[('a', '<f8'), ('b', '<i8')])
>>> d.dtype.names = 'apple', 'pear'
>>> d
rec.array([(1.0, 2), (3.0, 4)], 
      dtype=[('apple', '<f8'), ('pear', '<i8')])
Run Code Online (Sandbox Code Playgroud)


unu*_*tbu 2

mlab.csv2rec有一个names可用于设置列名称的参数:

r= mlab.csv2rec('HeightWeight.csv', delimiter= ',', 
                 names=['apple', 'pear'], 
                 skiprows=1)
Run Code Online (Sandbox Code Playgroud)

namesis not时Nonecsv2rec假设没有标题行。因此使用skiprows=1忽略标题行。