根据阈值将NumPy数组转换为0或1 [英] Convert NumPy array to 0 or 1 based on threshold

查看:497
本文介绍了根据阈值将NumPy数组转换为0或1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面有一个数组:

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

我想要的是基于阈值将此向量转换为二进制向量. 以threshold = 0.5为例,大于0.5的元素转换为1,否则为0.
输出向量应如下所示:

What I want is to convert this vector to a binary vector based on a threshold. take threshold=0.5 as an example, element that greater than 0.5 convert to 1, otherwise 0.
The output vector should like this:

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

我该怎么做?

推荐答案

np.where

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


使用astype

的布尔取暖


Boolean basking with astype

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


np.select


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,则这是最佳解决方案.


Special case: np.round

This is the best solution if your array values are floating values between 0 and 1 and your threshold is 0.5.

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

这篇关于根据阈值将NumPy数组转换为0或1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆