python:如何向numpy的记录数组添加列

3 投票
1 回答
3016 浏览
提问于 2025-04-18 14:07

我正在尝试给一个numpy记录添加一列。

这是我的代码:

import numpy
import numpy.lib.recfunctions
data=[[20140101,'a'],[20140102,'b'],[20140103,'c']]
data_array=numpy.array(data)
data_dtype=[('date',int),('type','|S1')]
data_rec=numpy.core.records.array(list(tuple(data_array.transpose())), dtype=data_dtype)
data_rec.date
data_rec.type

#Here, i will just try to make another field called copy_date that is a copy of the date    , just as an example

y=numpy.lib.recfunctions.append_fields(data_rec,'copy_date',data_rec.date,dtypes=data_rec.date.dtype,usemask=False)

现在看看输出结果

>>> type(y)
<type 'numpy.ndarray'>
>>> y.date
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'numpy.ndarray' object has no attribute 'date'
>>> y.copy_date
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'numpy.ndarray' object has no attribute 'copy_date'

y不再是像之前那样的记录类型了

>>> type(data_rec)
<class 'numpy.core.records.recarray'>

我好像失去了记录的功能,也就是不能通过属性来调用字段了。请问我该如何正确地给记录添加一列,并且还能调用字段呢?

另外,如果有人能告诉我上面代码中的usemask选项是干什么的,我会很感激。

谢谢

1 个回答

1

你可以在使用 numpy.lib.recfunctions.append_fields 的时候,传入 asrecarray=True 这个参数,这样就能得到一个记录数组(recarray)。

比如:

>>> y = numpy.lib.recfunctions.append_fields(data_rec, 'copy_date', data_rec.date, dtypes=data_rec.date.dtype, usemask=False, asrecarray=True)
>>> y.date
array([2, 2, 2])
>>> y
rec.array([(2, 'a', 2), (2, 'b', 2), (2, 'c', 2)], 
      dtype=[('date', '<i8'), ('type', '|S1'), ('copy_date', '<i8')])
>>> y.copy_date
array([2, 2, 2])

在 numpy 1.6.1 上测试过

撰写回答