[英]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.
说我有
a=np.random.randn(4,2)
数组a=np.random.randn(4,2)
,我想从100中减去每个负元素。如果我想从每个元素中减去100,那么我会使用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? 但是如果我想从100中减去每个元素怎么办?如何在不循环浏览每个元素的情况下做到这一点?
您可以使用相同的想法:
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: 您可以通过使用避免@ Akiiino的解决方案临时数组
out
和where
的论点np.ufunc
S:
np.subtract(100, a, out=a, where=a<0)
In general, the meaning of ufunc(a, b, out, where)
is roughly: 通常,
ufunc(a, b, out, where)
的含义大致为:
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 我们看到这里的速度提高了约15%
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.