[英]subtract element from number if element satisfies if condition numpy
說我有a=np.random.randn(4,2)
數組a=np.random.randn(4,2)
,我想從100中減去每個負元素。如果我想從每個元素中減去100,那么我會使用a[(a<0)] -=100.
但是如果我想從100中減去每個元素怎么辦?如何在不循環瀏覽每個元素的情況下做到這一點?
您可以使用相同的想法:
a[a<0] = 100 - a[a<0]
您可以通過使用避免@ Akiiino的解決方案臨時數組out
和where
的論點np.ufunc
S:
np.subtract(100, a, out=a, where=a<0)
通常, ufunc(a, b, out, where)
的含義大致為:
out[where] = ufunc(a[where], b[where])
比較速度:
In [1]: import numpy as np
In [2]: a = np.random.randn(10000, 2)
In [3]: b = a.copy() # so the that boolean mask doesn't change
In [4]: %timeit a[b < 0] = 100 - a[b < 0]
307 µs ± 1.53 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [5]: %timeit np.subtract(100, a, out=a, where=b < 0)
260 µs ± 39.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
我們看到這里的速度提高了約15%
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.