我们可以使用 NumPy 内置的 np.maximum,正是为此目的而制作的 -
np.maximum(array1, array2)
另一种方法是在 2D 堆叠数组上使用 NumPy ufunc np.max 并沿第一个轴使用 max-reduce (axis=0) -
np.max([array1,array2],axis=0)
100 万个数据集的时序 -
In [271]: array1 = np.random.randint(0,9,(1000000))
In [272]: array2 = np.random.randint(0,9,(1000000))
In [274]: %timeit np.maximum(array1, array2)
1000 loops, best of 3: 1.25 ms per loop
In [275]: %timeit np.max([array1, array2],axis=0)
100 loops, best of 3: 3.31 ms per loop
# @Eric Duminil's soln1
In [276]: %timeit np.where( array1 > array2, array1, array2)
100 loops, best of 3: 5.15 ms per loop
# @Eric Duminil's soln2
In [277]: magic = lambda x,y : np.where(x > y , x, y)
In [278]: %timeit magic(array1, array2)
100 loops, best of 3: 5.13 ms per loop
扩展到其他支持的 ufuncs
同样,np.minimum 用于在两个具有相同或可广播形状的数组之间查找元素最小值。所以,要找到array1 和array2 之间的元素最小值,我们需要:
np.minimum(array1, array2)
有关支持此功能的ufuncs 的完整列表,请参阅docs 并查找关键字:element-wise。 Grep-ing 对于那些,我得到了以下 ufunc:
加、减、乘、除、logaddexp、logaddexp2、true_divide、
floor_divide, 电源, 余数, mod, fmod, divmod, heaviside, gcd,
lcm,arctan2,hypot,bitwise_and,bitwise_or,bitwise_xor,left_shift,
右移,更大,更大,等于,更少,更少,等于,不等于,
等于,logical_and,logical_or,logical_xor,最大值,最小值,fmax,
fmin、copysign、nextafter、ldexp、fmod