更新时间:2022-12-19 22:49:24
We could use NumPy built-in np.maximum
, made exactly for that purpose -
np.maximum(array1, array2)
另一种方法是使用NumPy ufunc np.max
在2D
堆叠数组上,并且max-reduce
沿第一个轴(axis=0)
-
Another way would be to use the NumPy ufunc np.max
on a 2D
stacked array and max-reduce
along the first axis (axis=0)
-
np.max([array1,array2],axis=0)
一百万个数据集的时间-
Timings on 1 million datasets -
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
扩展到其他支持的功能
类似地,还有np.minimum
,用于在两个相同或可广播形状的数组之间查找元素方式的最小值.因此,要找到array1
和array2
之间的逐元素最小值,我们将有:
Similarly, there's np.minimum
for finding element-wise minimum values between two arrays of same or broadcastable shapes. So, to find element-wise minimum between array1
and array2
, we would have :
np.minimum(array1, array2)
有关支持此功能的ufuncs
的完整列表,请参考 docs
并查找关键字:element-wise
. Grep
-为此,我得到了以下ufuncs:
For a complete list of ufuncs
that support this feature, please refer to the docs
and look for the keyword : element-wise
. Grep
-ing for those, I got the following ufuncs :
加,减,乘,除,logaddexp,logaddexp2,true_divide, floor_divide,功率,余数,mod,fmod,divmod,heaviside,gcd, lcm,arctan2,hypo,bitwise_and,bitwise_or,bitwise_xor,left_shift, right_shift,更大,更大等于,更少,更少等于,不等于, 等于,逻辑与,逻辑或,逻辑异或,最大值,最小值,fmax, fmin,copysign,nextafter,ldexp,fmod
add, subtract, multiply, divide, logaddexp, logaddexp2, true_divide, floor_divide, power, remainder, mod, fmod, divmod, heaviside, gcd, lcm, arctan2, hypot, bitwise_and, bitwise_or, bitwise_xor, left_shift, right_shift, greater, greater_equal, less, less_equal, not_equal, equal, logical_and, logical_or, logical_xor, maximum, minimum, fmax, fmin, copysign, nextafter, ldexp, fmod