根据条件有效地反转列表中的浮点数 [英] Efficiently invert floats in a list based on a condition
问题描述
我有一个浮点数ndarray(a
)和一个0或1的列表(b
). a
和b
具有相同的长度,通常为1000.我想对索引与b
中的1对应的a
元素应用一个简单函数(例如,减去逆数). >
以下方法花费不到1毫秒的时间.有可能使其更快吗?
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
使用b
作为掩码,并相应地设置a
的单元格:
m = np.array(b).astype(bool)
a[m] = -1 / a[m]
更好的是,使用np.random.choice
初始化b
:
b = np.random.choice(2, 1000).astype(bool)
现在,您无需将b
转换为数组的开销,只需将其直接用于索引a
:
a[b] = -1 / a[b]
它在
中运行22.3 µs ± 501 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
I have one ndarray of floats (a
) and one list of 0 or 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
.
The following method takes a bit less than 1 millisecond. 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:
m = np.array(b).astype(bool)
a[m] = -1 / a[m]
Even better, initialise b
using np.random.choice
:
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
:
a[b] = -1 / a[b]
This runs in
22.3 µs ± 501 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
这篇关于根据条件有效地反转列表中的浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!