python bool 转vc int_的Python:转换布尔数组int数组

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?

In Scilab I can just use the command

>>> bool2s(y)

0. 0. 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?

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 arrays have an astype method. Just do y.astype(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])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值