gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:14:48 28 4
gpt4 key购买 nike

我是 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.])

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')])

关于python - 我可以重命名 numpy 记录数组中的字段吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14429992/

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