Kwo*_*olf 107 python integer boolean type-conversion scilab
我使用Scilab,并希望将一个布尔数组转换为一个整数数组:
>>> x = np.array([4, 3, 2, 1])
>>> y = 2 >= x
>>> y
array([False, False, True, True], dtype=bool)
Run Code Online (Sandbox Code Playgroud)
在Scilab中我可以使用:
>>> bool2s(y)
0. 0. 1. 1.
Run Code Online (Sandbox Code Playgroud)
或者甚至只是乘以1:
>>> 1*y
0. 0. 1. 1.
Run Code Online (Sandbox Code Playgroud)
在Python中是否有一个简单的命令,或者我是否必须使用循环?
Bre*_*arn 139
Numpy数组有一个astype方法.做吧y.astype(int).
请注意,根据您使用数组的内容,甚至可能不需要执行此操作.在许多情况下,Bool将自动提升为int,因此您可以将其添加到int数组而无需显式转换它:
>>> x
array([ True, False, True], dtype=bool)
>>> x + [1, 2, 3]
array([2, 2, 4])
Run Code Online (Sandbox Code Playgroud)
Suk*_*lra 43
该1*y方法也适用于Numpy:
>>> import numpy as np
>>> x = np.array([4, 3, 2, 1])
>>> y = 2 >= x
>>> y
array([False, False, True, True], dtype=bool)
>>> 1*y # Method 1
array([0, 0, 1, 1])
>>> y.astype(int) # Method 2
array([0, 0, 1, 1])
Run Code Online (Sandbox Code Playgroud)
如果您要求一种将Python列表从Boolean转换为int的方法,您可以使用map它:
>>> testList = [False, False, True, True]
>>> map(lambda x: 1 if x else 0, testList)
[0, 0, 1, 1]
>>> map(int, testList)
[0, 0, 1, 1]
Run Code Online (Sandbox Code Playgroud)
或者使用列表推导:
>>> testList
[False, False, True, True]
>>> [int(elem) for elem in testList]
[0, 0, 1, 1]
Run Code Online (Sandbox Code Playgroud)
cjm*_*cjm 18
使用numpy,您可以:
y = x.astype(int)
Run Code Online (Sandbox Code Playgroud)
如果您使用的是非numpy数组,则可以使用列表推导:
y = [int(val) for val in x]
Run Code Online (Sandbox Code Playgroud)
Gio*_*elm 12
大多数时候你不需要转换:
>>>array([True,True,False,False]) + array([1,2,3,4])
array([2, 3, 3, 4])
Run Code Online (Sandbox Code Playgroud)
正确的方法是:
yourArray.astype(int)
Run Code Online (Sandbox Code Playgroud)
要么
yourArray.astype(float)
Run Code Online (Sandbox Code Playgroud)
一个有趣的方法是
>>> np.array([True, False, False]) + 0
np.array([1, 0, 0])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
186997 次 |
| 最近记录: |