如何将布尔数组转换为int数组 [英] How to convert a boolean array to an int array

查看:279
本文介绍了如何将布尔数组转换为int数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Scilab,并希望将布尔数组转换为整数数组:

I use Scilab, and want to convert an array of booleans into an array of integers:

>>> x = np.array([4, 3, 2, 1])
>>> y = 2 >= x
>>> y
array([False, False,  True,  True], dtype=bool)

在Scilab中,我可以使用:

In Scilab I can use:

>>> bool2s(y)
0.    0.    1.    1.  

甚至只是乘以它1:

>>> 1*y
0.    0.    1.    1.  

是否有一个简单的命令这在Python中,还是我必须使用循环?

Is there a simple command for this in Python, or would I have to use a loop?

推荐答案

Numpy数组有一个 astype 方法。只需执行 y.astype(int)

Numpy arrays have an astype method. Just do y.astype(int).

请注意,甚至可能不需要执行此操作,具体取决于关于你使用数组的内容。在许多情况下,Bool将自动提升为int,因此您可以将其添加到int数组而无需显式转换它:

Note that it might not even be necessary to do this, depending on what you're using the array for. Bool will be autopromoted to int in many cases, so you can add it to int arrays without having to explicitly convert it:

>>> x
array([ True, False,  True], dtype=bool)
>>> x + [1, 2, 3]
array([2, 2, 4])

这篇关于如何将布尔数组转换为int数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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