bob*_*345 5 python arrays conditional numpy
我是NumPy的新手,我遇到了在numpy数组上运行一些条件语句的问题.假设我有3个numpy数组,如下所示:
A:
[[0, 4, 4, 2],
[1, 3, 0, 2],
[3, 2, 4, 4]]
Run Code Online (Sandbox Code Playgroud)
b:
[[6, 9, 8, 6],
[7, 7, 9, 6],
[8, 6, 5, 7]]
Run Code Online (Sandbox Code Playgroud)
而且,c:
[[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
Run Code Online (Sandbox Code Playgroud)
我有一个a和b的条件语句,其中我想使用b的值(如果满足a和b的条件)来计算c的值:
c[(a > 3) & (b > 8)]+=b*2
Run Code Online (Sandbox Code Playgroud)
我收到一个错误说:
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
ValueError: non-broadcastable output operand with shape (1,) doesn't match the broadcast shape (3,4)
Run Code Online (Sandbox Code Playgroud)
知道我怎么能做到这一点?
我想c的输出看起来如下:
[[0, 18, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
Run Code Online (Sandbox Code Playgroud)
Psi*_*dom 12
你可以使用numpy.where:
np.where((a > 3) & (b > 8), c + b*2, c)
#array([[ 0, 18, 0, 0],
# [ 0, 0, 0, 0],
# [ 0, 0, 0, 0]])
Run Code Online (Sandbox Code Playgroud)
或者算术上:
c + b*2 * ((a > 3) & (b > 8))
#array([[ 0, 18, 0, 0],
# [ 0, 0, 0, 0],
# [ 0, 0, 0, 0]])
Run Code Online (Sandbox Code Playgroud)
问题是您屏蔽了接收部件,但没有屏蔽发送器部件.结果是:
c[(a > 3) & (b > 8)]+=b*2
# ^ 1x1 matrix ^3x4 matrix
Run Code Online (Sandbox Code Playgroud)
尺寸不一样.如果您想要执行逐元素添加(基于您的示例),您也可以简单地将切片添加到右侧部分:
c[(a > 3) & (b > 8)]+=b[(a > 3) & (b > 8)]*2Run Code Online (Sandbox Code Playgroud)
或者提高效率:
mask = (a > 3) & (b > 8)
c[mask] += b[mask]*2Run Code Online (Sandbox Code Playgroud)