numpy 数组的条件操作

2022-01-20 00:00:00 python numpy arrays conditional

问题描述

我是 NumPy 的新手,在 numpy 数组上运行一些条件语句时遇到了问题.假设我有 3 个如下所示的 numpy 数组:

I'm new to NumPy, and I've encountered a problem with running some conditional statements on numpy arrays. Let's say I have 3 numpy arrays that look like this:

一个:

[[0, 4, 4, 2],
 [1, 3, 0, 2],
 [3, 2, 4, 4]]

b:

[[6, 9, 8, 6],
 [7, 7, 9, 6],
 [8, 6, 5, 7]]

和,c:

[[0, 0, 0, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 0]]

我有一个a和b的条件语句,我想用b的值(如果a和b的条件都满足的话)来计算c的值:

I have a conditional statement for a and b in which I would like to use the value of b (if the conditions of a and b are met) to calculate the value of c:

c[(a > 3) & (b > 8)]+=b*2

我收到一条错误消息:

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)

知道我该如何做到这一点吗?

Any idea how I can accomplish this?

我希望 c 的输出如下所示:

I would like the output of c to look as follows:

[[0, 18, 0, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 0]]


解决方案

可以使用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]])

或算术:

c + b*2 * ((a > 3) & (b > 8))
#array([[ 0, 18,  0,  0],
#       [ 0,  0,  0,  0],
#       [ 0,  0,  0,  0]])

相关文章