Python Numpy 结构化数组 (recarray) 切片赋值

6 投票
1 回答
2682 浏览
提问于 2025-04-16 00:05

下面这个例子展示了我想要做的事情:

>>> 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。我尝试了很多方法,但一直没有成功。有没有什么办法可以做到这一点?

谢谢,
Joon

1 个回答

5

当你写 test['ifAction'] 时,你是在查看数据的内容。
而当你写 test[['ifAction','ifDocu']] 时,你是在使用一种叫做“花式索引”的方法,这样会得到数据的一个副本。这个副本并没有什么用,因为修改副本不会改变原始数据。

所以,解决这个问题的方法是分别给 test['ifAction']test['ifDocu'] 赋值:

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 的这篇文章

撰写回答