【问题标题】:Pandas mapping to TRUE/FALSE as String, not BooleanPandas 映射到 TRUE/FALSE 作为字符串,而不是布尔值
【发布时间】:2017-08-04 22:47:24
【问题描述】:

当我尝试将 pandas 数据框中的某些列从“0”和“1”转换为“TRUE”和“FALSE”时,pandas 会自动将 dtype 检测为布尔值。我想将 dtype 保留为字符串,字符串为 'TRUE' 和 '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。我怎样才能防止这种情况发生?

【问题讨论】:

    标签: python pandas dictionary replace


    【解决方案1】:

    如果需要替换 booleanTrueFalse:

    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
    

    【讨论】:

    • 请注意带有替换的更简单的解决方案 - 将 .replace() 应用于 int 列将导致将 0 和 1 替换为布尔值:(
    猜你喜欢
    • 2015-02-21
    • 2018-03-10
    • 2013-10-11
    • 2011-12-28
    • 2011-04-27
    • 2019-06-09
    • 1970-01-01
    • 2019-08-16
    • 1970-01-01
    相关资源
    最近更新 更多