Python Numpy结构化数组(recarray)将值分配到切片中 [英] Python Numpy Structured Array (recarray) assigning values into slices
问题描述
以下示例显示了我想做什么:
The following example shows what I want to do:
>>> test
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)],
dtype=[('ifAction', '|i1'), ('ifDocu', '|i1'), ('ifComedy', '|i1')])
>>> test[['ifAction', 'ifDocu']][0]
(0, 0)
>>> test[['ifAction', 'ifDocu']][0] = (1,1)
>>> test[['ifAction', 'ifDocu']][0]
(0, 0)
因此,我想将值(1,1)
分配给test[['ifAction', 'ifDocu']][0]
. (最终,我想做类似test[['ifAction', 'ifDocu']][0:10] = (1,1)
的事情,为0:10
分配相同的值.我尝试了很多方法,但从未成功.有什么方法可以做到这一点?
So, I want to assign the values (1,1)
to test[['ifAction', 'ifDocu']][0]
. (Eventually, I want to do something like test[['ifAction', 'ifDocu']][0:10] = (1,1)
, assigning the same values for for 0:10
. I have tried many ways but never succeeded. Is there any way to do this?
谢谢你, 琼
推荐答案
当您说test['ifAction']
时,您将看到数据视图.
当您说test[['ifAction','ifDocu']]
时,您正在使用花式索引,因此会获得数据的副本.副本无济于事,因为修改副本会使原始数据保持不变.
When you say test['ifAction']
you get a view of the data.
When you say test[['ifAction','ifDocu']]
you are using fancy-indexing and thus get a copy of the data. The copy doesn't help you since modifying the copy leaves the original data unchanged.
因此,一种解决方法是分别为test['ifAction']
和test['ifDocu']
分配值:
So a way around this is to assign values to test['ifAction']
and test['ifDocu']
individually:
test['ifAction'][0]=1
test['ifDocu'][0]=1
例如:
import numpy as np
test=np.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)],
dtype=[('ifAction', '|i1'), ('ifDocu', '|i1'), ('ifComedy', '|i1')])
print(test[['ifAction','ifDocu']])
# [(0, 0) (0, 0) (0, 0) (0, 0) (0, 0) (0, 0) (0, 0) (0, 0) (0, 0) (0, 0)]
test['ifAction'][0]=1
test['ifDocu'][0]=1
print(test[['ifAction','ifDocu']][0])
# (1, 1)
test['ifAction'][0:10]=1
test['ifDocu'][0:10]=1
print(test[['ifAction','ifDocu']])
# [(1, 1) (1, 1) (1, 1) (1, 1) (1, 1) (1, 1) (1, 1) (1, 1) (1, 1) (1, 1)]
要深入了解,请参见这篇文章罗伯特·克恩(Robert Kern).
这篇关于Python Numpy结构化数组(recarray)将值分配到切片中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!