的Python:转换布尔数组int数组 [英] Python: convert boolean array to int array

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

问题描述

我使用的Scilab,并且是新到Python。如果我想转换一个布尔数组说:

I use Scilab, and am new to Python. If I wanted to convert a boolean array say:

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

到一个整数数组,我该怎么办?

into an integer array, what do I do?

在我的Scilab可以只使用命令

In Scilab I can just use the command

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

甚至只是由1乘以:

or even just multiply it by 1:

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

有没有这蟒蛇一个简单的命令?或者,我将不得不使用循环?

Is there a simple command for this in python? Or would I have to use loops?

感谢您。如果您知道任何很好的参考材料(网站,书籍,文章)获取到Python非程序员/ Scilab的(或Matlab)的用户,随时与我分享。

Thank you. If you know of any good reference material (websites, books, articles) for getting into Python for non-programmers / Scilab (or Matlab) users, feel free to share with me.

推荐答案

numpy的阵列有一个 astype 方法。只要做到 y.astype(INT)

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

请注意,它甚至可能没有必要做到这一点,取决于你所使用的为数组。布尔将autopromoted在许多情况下为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, e.g., 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])

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

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