如何在python中从布尔数组转换为int数组

Aka*_*uja 9 python numpy

我有一个Numpy二维数组,其中一列有布尔值,即True/ False.我想分别将它转换为整数1,0我该怎么办呢?

data[0::,2]是布尔,我试过

data[0::,2]=int(data[0::,2])
Run Code Online (Sandbox Code Playgroud)

,但它给了我错误:

TypeError: only length-1 arrays can be converted to Python scalars

我的前5行数组是:

[['0', '3', 'True', '22', '1', '0', '7.25', '0'],
 ['1', '1', 'False', '38', '1', '0', '71.2833', '1'],
 ['1', '3', 'False', '26', '0', '0', '7.925', '0'],
 ['1', '1', 'False', '35', '1', '0', '53.1', '0'],
 ['0', '3', 'True', '35', '0', '0', '8.05', '0']]
Run Code Online (Sandbox Code Playgroud)

kir*_*gin 10

好的,将任何数组类型更改为float的最简单方法是:

data.astype(float)

您的数组的问题是这float('True')是一个错误,因为'True'无法解析为浮点数.因此,最好的做法是修复数组生成代码以生成浮点数(或者至少是具有有效浮点字符串的字符串)而不是bools.

在此期间,您可以使用此功能来修复您的数组:

def boolstr_to_floatstr(v):
    if v == 'True':
        return '1'
    elif v == 'False':
        return '0'
    else:
        return v
Run Code Online (Sandbox Code Playgroud)

最后你像这样转换你的数组:

new_data = np.vectorize(boolstr_to_floatstr)(data).astype(float)
Run Code Online (Sandbox Code Playgroud)


asl*_*lan 7

boolarrayvariable.astype(int)的工作原理:

data = np.random.normal(0,1,(1,5))
threshold = 0
test1 = (data>threshold)
test2 = test1.astype(int)
Run Code Online (Sandbox Code Playgroud)

输出:

data = array([[ 1.766, -1.765,  2.576, -1.469,  1.69]])
test1 = array([[ True, False,  True, False,  True]], dtype=bool)
test2 = array([[1, 0, 1, 0, 1]])
Run Code Online (Sandbox Code Playgroud)