如何在Numpy中掩盖记录数组的元素? [英] How can I mask elements of a record array in Numpy?
问题描述
我了解如何创建掩码数组,并且我想在记录数组中使用掩码,以便可以使用命名属性访问此数据.从蒙版数组创建记录数组时,蒙版似乎丢失"了:
I understand how to create a masked array, and I would like to use masking in a record array so that I can access this data using named attributes. The masking seems to be "lost" when I create a record array from a masked array:
>>> data = np.ma.array(np.ma.zeros(30, dtype=[('date', '|O4'), ('price', '<f8')]),mask=[i<10 for i in range(30)])
>>> data
masked_array(data = [(--, --) (--, --) (--, --) (--, --) (--, --) (--, --) (--, --) (--, --)
(--, --) (--, --) (0, 0.0) (0, 0.0) (0, 0.0) (0, 0.0) (0, 0.0) (0, 0.0) (0, 0.0) (0, 0.0) (0, 0.0) (0, 0.0) (0, 0.0) (0, 0.0) (0, 0.0) (0, 0.0)
(0, 0.0) (0, 0.0) (0, 0.0) (0, 0.0) (0, 0.0) (0, 0.0)],
mask = [(True, True) (True, True) (True, True) (True, True) (True, True)
(True, True) (True, True) (True, True) (True, True) (True, True)
(False, False) (False, False) (False, False) (False, False) (False, False)
(False, False) (False, False) (False, False) (False, False) (False, False)
(False, False) (False, False) (False, False) (False, False) (False, False)
(False, False) (False, False) (False, False) (False, False) (False, False)],
fill_value = ('?', 1e+20),
dtype = [('date', '|O4'), ('price', '<f8')])
>>> r = data.view(np.recarray)
>>> r
rec.array([(0, 0.0), (0, 0.0), (0, 0.0), (0, 0.0), (0, 0.0), (0, 0.0),
(0, 0.0), (0, 0.0), (0, 0.0), (0, 0.0), (0, 0.0), (0, 0.0),
(0, 0.0), (0, 0.0), (0, 0.0), (0, 0.0), (0, 0.0), (0, 0.0),
(0, 0.0), (0, 0.0), (0, 0.0), (0, 0.0), (0, 0.0), (0, 0.0),
(0, 0.0), (0, 0.0), (0, 0.0), (0, 0.0), (0, 0.0), (0, 0.0)],
dtype=[('date', '|O4'), ('price', '<f8')])
当我访问记录时,数据不会被屏蔽:
When I access a record the data is not masked:
>>> r.date[0]
0
与原始数组不同:
>>> data['date'][0]
masked_array(data = --,
mask = True,
fill_value = 1e+20)
fill_value = 1e+20)
我该怎么办?记录数组不支持屏蔽吗?在网络上浏览时,我看到了一些代码示例,它们似乎暗示了其他方面的含义,但并不是很清楚.希望我能在这里得到一个很好的答案.
What can I do? Does the record array not support masking? Browsing on the web I have seen some code examples that seem to suggest otherwise, but it wasn't very clear. Hoping I can get a good answer here.
推荐答案
I haven't found much documentation on numpy.ma.mrecords.MaskedRecords, except for a brief mention here. You can find some examples on how to use it by studying the unit tests that come with numpy. (e.g.
/usr/lib/python2.6/dist-packages/numpy/ma/tests/test_mrecords.py
).
import numpy as np
import numpy.ma.mrecords as mrecords
data = np.ma.array(
np.ma.zeros(30, dtype=[('date', '|O4'), ('price', '<f8')]),
mask=[i<10 for i in range(30)])
r = data.view(mrecords.mrecarray)
print(r.date[0])
# --
这篇关于如何在Numpy中掩盖记录数组的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!