Python 我可以重命名numpy记录数组中的字段吗
我是python新手,因此这听起来可能非常基本。我已经使用csv2rec导入了一个csv文件。第一行有标题。我想将标题更改为“x”、“y”、“z”。最好的方法是什么Python 我可以重命名numpy记录数组中的字段吗,python,numpy,matplotlib,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
>>> 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
您可以简单地分配给
.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.])
有一个names
参数,可用于设置列名:
r= mlab.csv2rec('HeightWeight.csv', delimiter= ',',
names=['apple', 'pear'],
skiprows=1)
当
names
不是None
时,csv2rec
假定没有标题行。因此,使用skiprows=1
忽略标题行。为此,在numpy.lib.recfunctions
中有一个rename\u fields
方法。它也适用于屏蔽阵列
import numpy as np
import numpy.lib.recfunctions as rfn
ab = np.ma.zeros(3, dtype=[('a', 'f4'), ('b', 'i4')])
xy = rfn.rename_fields(ab, {'a': 'x', 'b': 'y'})
print(ab.dtype, ab.mask.dtype)
print(xy.dtype, xy.mask.dtype)
输出:
[('a', '<f4'), ('b', '<i4')] [('a', '?'), ('b', '?')]
[('x', '<f4'), ('y', '<i4')] [('x', '?'), ('y', '?')]
[('a',”如果数组是掩码数组,则需要对d.mask.dtype.names
[('a', '<f4'), ('b', '<i4')] [('a', '?'), ('b', '?')]
[('x', '<f4'), ('y', '<i4')] [('x', '?'), ('y', '?')]