本文介绍了numpy 数组的条件操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!
问题描述
我是 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]])
这篇关于numpy 数组的条件操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!