蟒蛇:如何添加列记录numpy的阵列 [英] python: how to add column to record array in numpy

查看:446
本文介绍了蟒蛇:如何添加列记录numpy的阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一列添加到numpy的记录。

I am trying to add a column to a numpy record.

这是我的code:

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

我似乎失去记录的能力,这是调用由属性的字段。
我该如何正确列添加到一个记录,并能够调用的领域?

I seem to have lost the record abilities, which is to call the fields by the attribute. How can I correctly add a column to a record and be able to call the fields?

另外,我会很高兴,如果有人能告诉我usemask选项确实在上述code的内容。

Also, I'd be happy if someone can tell me what the usemask option does in the above code.

感谢

推荐答案

您可以通过 asrecarray = TRUE 来得到一个recarray背出 numpy的的.lib.recfunctions.append_fields

You can pass asrecarray=True to get a recarray back out of numpy.lib.recfunctions.append_fields.

例如:

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

这篇关于蟒蛇:如何添加列记录numpy的阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆