如何将布尔数组转换为int数组

2024-04-20 02:02:52 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

在科学实验室,我可以使用:

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

或者把它乘以1:

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

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


Tags: 命令falsetruenp整数科学数组array
3条回答

Numpy数组有一个astype方法。只要做y.astype(int)

请注意,根据数组的用途,甚至可能不需要这样做。在许多情况下,Bool将自动提示为int,因此您可以将其添加到int数组,而无需显式转换它:

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

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]) 

如果您想要将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]

或使用列表理解:

>>> testList
[False, False, True, True]
>>> [int(elem) for elem in testList]
[0, 0, 1, 1]

使用numpy,您可以执行以下操作:

y = x.astype(int)

如果使用的是非numpy数组,则可以使用list comprehension

y = [int(val) for val in x]

相关问题 更多 >