问题描述
我正在尝试遍历numpy数组并生成一个输出,该输出的条件类似于以下所述:
I am trying to iterate over numpy arrays and generate an output, which has conditions similar to that described below:
min1 = 3
max1 = 1
a1 = np.array([1, 2, 5, 3, 4])
a2 = np.array([5, 2, 6, 2, 1])
output = np.zeros(5)
for i in range(0, 5):
if((a1[i] - a2[i]) > min1):
output[i] = 3 * (a1[i] - a2[i])
if((a1[i] - a2[i]) < max1):
output = 5 * (a1[i] - a2[i])
我需要优化上面的代码,以便我将numpy
功能发挥到最好,并避免使用循环.我该怎么办?
I need to optimize the above code, so that I utilize the numpy
functionalities as the best and also avoid using a loop. How should I do it?
推荐答案
虽然像select
和where
这样的函数可以压缩代码,但我认为了解如何使用基本布尔掩码来实现此目的是一个好主意.它适用于很多情况,并且几乎总是一样快.
While functions like select
and where
can condense the code, I think it's a good idea to know how to do this with basic boolean masking. It's applicable in many cases, and nearly always as fast.
计算多次使用的差异:
In [432]: diff = a1-a2
In [433]: diff
Out[433]: array([-4, 0, -1, 1, 3])
In [435]: output = np.zeros_like(a1)
找到满足第一个条件的情况,并设置output
的相应元素:
find those cases where it meets the first condition, and set the corresponding elements of output
:
In [436]: mask1 = diff>min1
In [437]: output[mask1] = 3*diff[mask1]
重复第二个条件
In [438]: mask2 = diff<max1
In [439]: output[mask2] = 5*diff[mask2]
,如果还有更多条件,请再次输入.
and again if there are more conditions.
In [440]: output
Out[440]: array([-20, 0, -5, 0, 0])
在此示例中,只有-4和-1满足条件2,而没有条件1.
In this example, only the -4 and -1 met condition 2, and none condition 1.
这篇关于python numpy:在不使用循环的情况下针对不同的条件进行迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!