简体   繁体   English

Python Numpy结构化数组(重新排列)将值分配到切片中

[英]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)

So, I want to assign the values (1,1) to test[['ifAction', 'ifDocu']][0] . 所以,我想将值(1,1)分配给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', 'ifDocu']][0:10] = (1,1) ,为0:10指定相同的值。我尝试了很多方法但从未成功了。有没有办法做到这一点?

Thank you, Joon 谢谢你,Joon

When you say test['ifAction'] you get a view of the data. 当你说test['ifAction']你会看到数据。 When you say test[['ifAction','ifDocu']] you are using fancy-indexing and thus get a copy of the data. 当你说test[['ifAction','ifDocu']]你正在使用花式索引,从而获得数据的副本。 The copy doesn't help you since modifying the copy leaves the original data unchanged. 副本对您没有帮助,因为修改副本会使原始数据保持不变。

So a way around this is to assign values to test['ifAction'] and test['ifDocu'] individually: 所以解决这个问题的方法是为test['ifAction']分配值并分别test['ifDocu']

test['ifAction'][0]=1
test['ifDocu'][0]=1

For example: 例如:

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

For a deeper look under the hood, see this post by Robert Kern . 有关引擎盖下的更深入了解,请参阅Robert Kern撰写的这篇文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM