在混合数据类型的数据帧中将所有出现的True/False转换为1/0

2024-09-30 02:30:10 发布

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

我有一个数据框,大约有100列,有一些布尔列和一些字符。我想用1/0替换所有值为True/False和-1的布尔值。我想将它应用于整个数据帧而不是单个列。

我在这里看到了一些解决方案,比如将列转换为整数。但我想避免穿过100个柱子的练习。

以下是我试过但没有成功的东西:

test.applymap(lambda x: 1 if x=='True' else x)
test.applymap(lambda x: 0 if x=='False' else x)

但是dataframe测试仍然有True/False


Tags: 数据lambdatestfalsetruedataframeif整数
3条回答

默认情况下,applymap不在适当位置,它将返回一个新的数据帧。

正确的方法:

test = test.applymap(lambda x: 1 if x == True else x)
test = test.applymap(lambda x: 0 if x == False else x)

或者

test = test.applymap(lambda x: 1 if x == True else x).test.applymap(lambda x: 0 if x=='False' else x)

或者只是

test.applymap(lambda x: 1 if x == True else x, inplace=True)
test.applymap(lambda x: 0 if x == False else x, inplace=True)


尽管replace似乎是实现这一目标的最佳方法:

test.replace(False, 0, inplace=True)

定义一个函数,该函数在数据帧的每一列中循环.replace():

def replace_boolean(data):
    for col in data:
        data[col].replace(True, 1, inplace=True)
        data[col].replace(False, 0, inplace=True)

replace_boolean(test)

对于单个列,目前最简单的方法是转换列类型。Pandas足够聪明,能够正确映射布尔值以进行int。

df.column_name = df.column_name.astype(int)

如果df.column_name以Boolean开头,则在转换为类型int后,它将变为零和一

相关问题 更多 >

    热门问题