numpy 数组的条件操作

Conditional operations on numpy arrays(numpy 数组的条件操作)
本文介绍了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 数组的条件操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)