猿问

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

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采用与一样的方法where呢?


白衣染霜花
浏览 149回答 1
1回答

GCT1015

使用numpy的内置的逐元素maximum和minimum-他们比快where。numpy文档中的注释最大程度地证实了这一点:等效于np.where(x1> x2,x1,x2),但速度更快,并且可以正常广播。您想要的第一个测试行将是这样的:fmin = np.minimum(f1, f2); fmax = np.maximum(f1, f2)我自己的结果表明,这样做的速度要快得多。请注意,minimum和maximum将任意n维数组上工作,只要这两个参数是相同的形状。Using amax&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 3.506Using sort&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 1.830Using where&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;0.635Using numpy maximum, minimum&nbsp; 0.178
随时随地看视频慕课网APP

相关分类

Python
我要回答