根据阈值将NumPy数组转换为0或1。

42

我有下面这个数组:

a=np.array([0.1, 0.2, 0.3, 0.7, 0.8, 0.9])

我想要的是将这个向量根据阈值转换成二元向量。 以阈值为0.5为例,大于0.5的元素转换为1,否则为0。
输出向量应该如下所示:

a_output = [0, 0, 0, 1, 1, 1]

我该如何做到这一点?


1
这个回答解决了你的问题吗?如果条件满足,替换Numpy元素 - Georgy
2个回答

81

np.where

np.where(a > 0.5, 1, 0)
# array([0, 0, 0, 1, 1, 1])

使用astype进行布尔值转换

(a > .5).astype(int)
# array([0, 0, 0, 1, 1, 1])

np.select

np.select([a <= .5, a>.5], [np.zeros_like(a), np.ones_like(a)])
# array([ 0.,  0.,  0.,  1.,  1.,  1.])

特殊情况: np.round

如果你的数组值是介于0和1之间的浮点数,并且你的阈值为0.5,那么这是最佳解决方案。

a.round()
# array([0., 0., 0., 1., 1., 1.])

哪种方法在使用'dtype'为'uint8'时速度最快?np.select方法默认返回'uint8',但看起来更加复杂。 - user3613932
如果您希望获得一个dtype为“bool”的Numpy数组,则a>0.5将为您提供该数组。 - user3613932
@user3613932 我之前写过这个答案,如果我没记错的话,你可以使用 > .5 来获取一个布尔掩码,然后调用 .view 将视图更改为 uint8,这应该比 astype 更快...看一下,如果不行就告诉我。 - cs95
根据官方文档,不确定viewastype相比安全性如何。 astype会创建一个新的副本,而view则利用原始变量的内存。 - user3613932

0
你可以使用来自 sklearn.preprocessing 模块的 binarize。但是,只有当你想要最终值为二进制即“0”或“1”时,它才会起作用。上面提供的答案也很适用于非二进制结果。
from sklearn.preprocessing import binarize

a = np.array([0.1, 0.2, 0.3, 0.7, 0.8, 0.9]).reshape(1,-1)
x = binarize(a) 
a_output = np.ravel(x)
print(a_output) 

#everything together 
a_output = np.ravel(binarize(a.reshape(1,-1), 0.5))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接