假设你有一个 numpy array(n,n) 即。
x = np.arange(25).reshape(5,5)
然后用 -5 到 5 之间的随机整数填充 x。有没有一种方法可以使用 bool 掩码,以便我的所有 0 值都变为 1,并且所有非零数字都变为 0?(即,如果[index]>0 或 [index]<0,[index]=0,如果 [index]=0 则 [index]=1)
我知道您可以使用迭代来更改每个元素,但我的目标是速度,因此我希望从最终脚本中消除尽可能多的循环。
编辑:当然,只要牢记速度/效率,也可以接受其他想法
最佳答案
首先,您可以使用 np.random.randint
直接实例化数组:
# Note: the lower limit is inclusive while the upper limit is exclusive
x = np.random.randint(-5, 6, size=(5, 5))
为了真正完成工作,也许可以将类型转换为 bool,再将类型转换回来,然后取反?
res = 1 - x.astype(bool).astype(int)
或者,你可以更明确一点:
x[x != 0] = 1
res = 1 - x
但是第二种方法似乎花费了两倍多的时间:
>>> n = 1000
>>> a = np.random.randint(-5, 6, (n, n))
>>> %timeit a.astype(bool).astype(int)
1000 loops, best of 3: 1.58 ms per loop
>>> %timeit a[a != 0] = 1
100 loops, best of 3: 4.61 ms per loop
关于用于绝对值的 Python numpy bool 掩码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30656247/