numpy的多个切片布尔 [英] numpy multiple slicing booleans
问题描述
我无法在numpy数组中编辑值
I'm having trouble editing values in a numpy array
import numpy as np
foo = np.ones(10,10,2)
foo[row_criteria, col_criteria, 0] += 5
foo[row_criteria,:,0][:,col_criteria] += 5
row_criteria和col_criteria是布尔数组(1D).在第一种情况下,我得到
row_criteria and col_criteria are boolean arrays (1D). In the first case I get a
形状不匹配:无法将对象广播为单个形状"错误
"shape mismatch: objects cannot be broadcast to a single shape" error
在第二种情况下,根本不会应用+ = 5.
In the second case, += 5 doesn't get applied at all. When I do
foo[row_criteria,:,0][:,col_criteria] + 5
我得到了修改后的返回值,但是就地修改该值似乎不起作用...
I get a modified return value but modifying the value in place doesn't seem to work...
有人可以解释如何解决此问题吗?谢谢!
Can someone explain how to fix this? Thanks!
推荐答案
您要:
foo[np.ix_(row_criteria, col_criteria, [0])] += 5
要了解其工作原理,请举以下示例:
To understand how this works take this example:
import numpy as np
A = np.arange(25).reshape([5, 5])
print A[[0, 2, 4], [0, 2, 4]]
# [0, 12, 24]
# The above example gives the the elements A[0, 0], A[2, 2], A[4, 4]
# But what if I want the "outer product?" ie for [[0, 2, 4], [1, 3]] i want
# A[0, 1], A[0, 3], A[2, 1], A[2, 3], A[4, 1], A[4, 3]
print A[np.ix_([0, 2, 4], [1, 3])]
# [[ 1 3]
# [11 13]
# [21 23]]
同样的事情也适用于布尔索引.同样,np.ix_
并没有做任何真正令人惊奇的事情,它只是重塑了其参数,以便可以相互广播:
The same thing works with boolean indexing. Also np.ix_
doesn't do anything really amazing, it just reshapes it's arguments so they can be broadcast against each other:
i, j = np.ix_([0, 2, 4], [1, 3])
print i.shape
# (3, 1)
print j.shape
# (1, 2)
这篇关于numpy的多个切片布尔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!