Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我可以重命名numpy记录数组中的字段吗_Python_Numpy_Matplotlib - Fatal编程技术网

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

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

我是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

您可以简单地分配给
.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', '?')]