Pandas 映射到 TRUE/FALSE 作为字符串,而不是布尔值 [英] Pandas mapping to TRUE/FALSE as String, not Boolean

查看:33
本文介绍了Pandas 映射到 TRUE/FALSE 作为字符串,而不是布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试将 pandas 数据框中的某些列从0"和1"转换为TRUE"和FALSE"时,pandas 会自动将 dtype 检测为布尔值.我想将 dtype 保留为字符串,字符串为TRUE"和FALSE".

When I try to convert some columns in a pandas dataframe from '0' and '1' to 'TRUE' and 'FALSE', pandas automatically detects dtype as boolean. I want to keep dtype as string, with the strings 'TRUE' and 'FALSE'.

见下面的代码:

booleanColumns = pandasDF.select_dtypes(include=[bool]).columns.values.tolist()
booleanDictionary = {'1': 'TRUE', '0': 'FALSE'}

pandasDF.to_string(columns = booleanColumns)

for column in booleanColumns:
    pandasDF[column].map(booleanDictionary)

不幸的是,python 在最后一次操作时自动将 dtype 转换为 boolean.我怎样才能防止这种情况?

Unfortunately, python automatically converts dtype to boolean with the last operation. How can I prevent this?

推荐答案

如果需要替换 booleanTrueFalse:

If need replace boolean values True and False:

booleandf = pandasDF.select_dtypes(include=[bool])
booleanDictionary = {True: 'TRUE', False: 'FALSE'}

for column in booleandf:
    pandasDF[column] = pandasDF[column].map(booleanDictionary)

示例:

pandasDF = pd.DataFrame({'A':[True,False,True],
                   'B':[4,5,6],
                   'C':[False,True,False]})

print (pandasDF)
       A  B      C
0   True  4  False
1  False  5   True
2   True  6  False

booleandf = pandasDF.select_dtypes(include=[bool])
booleanDictionary = {True: 'TRUE', False: 'FALSE'}

#loop by df is loop by columns, same as for column in booleandf.columns:
for column in booleandf:
    pandasDF[column] = pandasDF[column].map(booleanDictionary)

print (pandasDF)
       A  B      C
0   TRUE  4  FALSE
1  FALSE  5   TRUE
2   TRUE  6  FALSE

使用 replace by dict:

booleanDictionary = {True: 'TRUE', False: 'FALSE'}
pandasDF = pandasDF.replace(booleanDictionary)
print (pandasDF)
       A  B      C
0   TRUE  4  FALSE
1  FALSE  5   TRUE
2   TRUE  6  FALSE

这篇关于Pandas 映射到 TRUE/FALSE 作为字符串,而不是布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆