用于绝对值的 Python numpy bool 掩码

标签 python arrays numpy indexing masking

假设你有一个 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/

相关文章:

Python pandas 根据时间间隔减少回填,直到达到一定数量

python - PyCrypto:仅使用文件中的公钥解密(无私钥+公钥)

C++ 将 std::string 复制到没有空终止的 char 数组

python - 查找边界之间错误颜色的像素

python - Cython - 字典键和值静态类型定义

python - Asyncmongo 不返回 _id

mysql - 你如何在 (?) 调用中执行 SQL 查找?

c - 如何在c中初始化未知大小的数组

python - 形状不匹配 Numpy

Python:matplotlib 'numpy.ndarray' 对象没有属性 'has_data'