有没有更快的方法来分离两个数组的最小值和最大值?

2024-04-23 09:00:46 发布

您现在位置:Python中文网/ 问答频道 /正文

In [3]: f1 = rand(100000)
In [5]: f2 = rand(100000)

# Obvious method:
In [12]: timeit fmin = np.amin((f1, f2), axis=0); fmax = np.amax((f1, f2), axis=0)
10 loops, best of 3: 59.2 ms per loop

In [13]: timeit fmin, fmax = np.sort((f1, f2), axis=0)
10 loops, best of 3: 30.8 ms per loop

In [14]: timeit fmin = np.where(f2 < f1, f2, f1); fmax = np.where(f2 < f1, f1, f2)
100 loops, best of 3: 5.73 ms per loop


In [36]: f1 = rand(1000,100,100)

In [37]: f2 = rand(1000,100,100)

In [39]: timeit fmin = np.amin((f1, f2), axis=0); fmax = np.amax((f1, f2), axis=0)
1 loops, best of 3: 6.13 s per loop

In [40]: timeit fmin, fmax = np.sort((f1, f2), axis=0)
1 loops, best of 3: 3.3 s per loop

In [41]: timeit fmin = np.where(f2 < f1, f2, f1); fmax = np.where(f2 < f1, f1, f2)
1 loops, best of 3: 617 ms per loop

比如,也许有一种方法可以同时执行where命令,并返回2次?在

为什么amin与{}的实现方式不同,如果它快得多呢?在


Tags: ofinloopnpwheref2f1best
1条回答
网友
1楼 · 发布于 2024-04-23 09:00:46

使用numpy内置的元素maximum和{}-它们比where快。 numpy docs for maximum中的注释证实了这一点:

Equivalent to np.where(x1 > x2, x1, x2), but faster and does proper broadcasting.

第一次测试所需的线路如下:

fmin = np.minimum(f1, f2); fmax = np.maximum(f1, f2)

我自己的结果显示这个速度要快得多。请注意,minimum和{}将在任何n维数组上工作,只要这两个参数的形状相同。在

^{pr2}$

相关问题 更多 >