Python 若元素满足if条件numpy,则从数字中减去元素

Python 若元素满足if条件numpy,则从数字中减去元素,python,numpy,Python,Numpy,假设我有arraya=np.random.randn(4,2),我想从100中减去每个负元素。 如果我想从每个元素中减去100,那么我将使用a[(a你可以使用相同的想法: a[a<0] = 100 - a[a<0] a[a您可以使用相同的想法: a[a<0] = 100 - a[a<0] a[a通过使用np.ufuncs的out和where参数,可以避免@akiino解决方案中的临时数组: np.subtract(100, a, out=a, where=a<0

假设我有array
a=np.random.randn(4,2)
,我想从100中减去每个负元素。
如果我想从每个元素中减去100,那么我将使用
a[(a你可以使用相同的想法:

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

a[a您可以使用相同的想法:

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

a[a通过使用
np.ufunc
s的
out
where
参数,可以避免@akiino解决方案中的临时数组:

np.subtract(100, a, out=a, where=a<0)
比较速度:

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)
[1]中的
:将numpy作为np导入
[2]中:a=np.random.randn(10000,2)
在[3]:b=a.copy()#中,这样布尔掩码就不会改变
在[4]:%timeit a[b<0]=100-a[b<0]
每个回路307µs±1.53µs(7次运行的平均±标准偏差,每个1000个回路)
[5]中:%timeit np.subtract(100,a,out=a,其中=b<0)
每个回路260µs±39.7µs(7次运行的平均±标准偏差,每个1000个回路)

我们看到这里有大约15%的速度提升

您可以通过使用
out
where
np.ufunc
s参数来避免@akiino解决方案中的临时数组:

np.subtract(100, a, out=a, where=a<0)
比较速度:

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)
[1]中的
:将numpy作为np导入
[2]中:a=np.random.randn(10000,2)
在[3]:b=a.copy()#中,这样布尔掩码就不会改变
在[4]:%timeit a[b<0]=100-a[b<0]
每个回路307µs±1.53µs(7次运行的平均±标准偏差,每个1000个回路)
[5]中:%timeit np.subtract(100,a,out=a,其中=b<0)
每个回路260µs±39.7µs(7次运行的平均±标准偏差,每个1000个回路)

我们看到这里有大约15%的速度提升

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