Pandas映射为TRUE / FALSE作为String,而不是布尔

时间:2017-03-14 14:28:05

标签: python pandas dictionary replace

当我尝试转换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。我该如何防止这种情况?

1 个答案:

答案 0 :(得分:14)

如果需要替换func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) { print("\(entry.value) in \(yourArray[entry.xIndex])") } booleanTrue

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 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