以最有效的方式从数字numpy数组中获取0和1(整数bool)

Pau*_*nto 2 python numpy

我有非小(10 ^ 6)numpy数组,然后我做了一些计算.如果值大于某个值X,则其中一个函数返回0,否则返回1.我理解这个简单的bool检查完成工作:

x = np.arange(100)
x = np.array(x > X, dtype=int)
Run Code Online (Sandbox Code Playgroud)

但是,鉴于我正在创建一个新阵列并进行转换,这似乎非常浪费.关于如何做到的任何想法?沿着x.round()行的东西(但是会返回0或1).

或者我的担忧完全没有根据?

谢谢!P

PS:是的,numpy是必需的.

Rob*_*ern 5

很多时候,你可以绕过bool阵列逃脱.当用于对数值数组的算术运算时,bool数组将根据需要进行向上处理True,1并将False其视为和0.

但是如果你真的需要最有效的方法来获得一个真正的int数组,那就使用np.greater()ufunc.与所有ufuncs一样,它接受一个out=关键字参数,该参数将用作预先分配的数组来填充结果.它将动态转换每个元素,因此bool不会创建任何中间数组.

[~]
|1> import numpy as np

[~]
|2> x = np.arange(10)

[~]
|3> output = np.empty(x.shape, dtype=int)

[~]
|4> np.greater(x, 5, out=output)
array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1])

[~]
|5> output
array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1])
Run Code Online (Sandbox Code Playgroud)