繁体   English   中英

如果条件满足numpy,则从元素中减去元素

[英]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的解决方案临时数组outwhere的论点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.

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