我们可以使用内置的 NumPynp.maximum https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.maximum.html,正是为此目的而制作的 -
np.maximum(array1, array2)
另一种方法是使用 NumPy ufuncnp.max https://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.amax.html#numpy.amax on a 2D
堆叠数组和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
扩展到其他支持 ufunc
同样,还有np.minimum
用于查找两个相同或可广播形状的数组之间的元素最小值。因此,要找到之间的元素最小值array1
and array2
, 我们会有 :
np.minimum(array1, array2)
如需完整列表ufuncs
支持此功能的,请参考docs https://www.numpy.org/devdocs/reference/ufuncs.html并寻找关键字:element-wise
. Grep
- 对于这些,我得到了以下 ufuncs :
加、减、乘、除、logaddexp、logaddexp2、true_divide、
Floor_divide、幂、余数、mod、fmod、divmod、heaviside、gcd、
lcm、arctan2、hypot、按位与、按位或、按位异或、左移、
右移、更大、更大_等于、更少、更少_等于、不等于、
等于、逻辑与、逻辑或、逻辑异或、最大值、最小值、fmax、
fmin、copysign、nextafter、ldexp、fmod