简体   繁体   English

根据条件有效地反转列表中的浮点数

[英]Efficiently invert floats in a list based on a condition

I have one ndarray of floats ( a ) and one list of 0 or 1 ( b ). 我有一个浮点数ndarray( a )和一个0或1( b )的列表。 a and b have the same length, typically 1000. I would like to apply a simple function (such as minus the inverse) to the elements of a whose index correspond to 1 in b . ab具有相同的长度,通常为1000。我想对索引与b 1对应的a的元素应用一个简单的函数(例如,减去逆数)。

The following method takes a bit less than 1 millisecond. 以下方法花费不到1毫秒的时间。 Would it be possible to make it faster? 是否有可能使其更快?

import numpy as np

# generate dummy data
n = 1000
a = np.random.uniform(low=0, high=10, size=n)
b = np.random.choice(2, 1000)

# map the function
start = time.time()
out = [a[i] if b[i] == 0 else -1/a[i] for i in range(n)]
print time.time() - start

Use b as a mask, and set a 's cells accordingly: 使用b作为遮罩,并相应设置a的单元格:

m = np.array(b).astype(bool)
a[m] = -1 / a[m]

Even better, initialise b using np.random.choice : 更好的是,使用np.random.choice初始化b

b = np.random.choice(2, 1000).astype(bool)

Now, you don't need the overhead of converting b to an array, just use it directly to index a : 现在,您无需将b转换为数组的开销,只需将其直接用于索引a

a[b] = -1 / a[b]

This runs in 这在

22.3 µs ± 501 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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