This question already has answers here:
How to convert true false values in dataframe as 1 for true and 0 for false
(12个答案)
在6个月前关闭。
我有一个数据框,它有大约100列,其中有一些 bool 列和一些字符。我想将所有具有值True/False和-1的 bool 值替换为1/0。我想将其应用于整个数据框而不是单个列。
我在这里看到了一些解决方案,例如将列转换为整数。但是我想避免遍历100列的练习。
这是我尝试失败的内容:
或者
或简单地
尽管
(12个答案)
在6个月前关闭。
我有一个数据框,它有大约100列,其中有一些 bool 列和一些字符。我想将所有具有值True/False和-1的 bool 值替换为1/0。我想将其应用于整个数据框而不是单个列。
我在这里看到了一些解决方案,例如将列转换为整数。但是我想避免遍历100列的练习。
这是我尝试失败的内容:
test.applymap(lambda x: 1 if x=='True' else x)
test.applymap(lambda x: 0 if x=='False' else x)
但是数据帧测试仍然具有True/False 最佳答案
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)
关于python - 将具有混合数据类型的数据帧中所有出现的True/False转换为1/0,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38499747/