简体   繁体   中英

subtract element from number if element satisfies if condition numpy

say I have array a=np.random.randn(4,2) and I want to subtract each negative element from 100. if I want to subtract 100 from each element then I would use a[(a<0)] -=100. but what if I want to subtract each element from 100. How can I do it without looping through each element?

您可以使用相同的想法:

a[a<0] = 100 - a[a<0]

You can avoid the temporary array in @Akiiino's solution by using the out and where arguments of np.ufunc s:

np.subtract(100, a, out=a, where=a<0)

In general, the meaning of ufunc(a, b, out, where) is roughly:

out[where] = ufunc(a[where], b[where])

Comparing the speed:

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)

We see that there's a ~15% speed boost here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM