开发者

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]. (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?

Thank you, Joon


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.

So a way around this is to assign values to test['ifAction'] and test['ifDocu'] individually:

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 .

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜