Den*_*tes 9 python dictionary replace pandas
当我尝试将pandas数据帧中的某些列从"0"和"1"转换为"TRUE"和"FALSE"时,pandas会自动将dtype检测为boolean.我想将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)
Run Code Online (Sandbox Code Playgroud)
不幸的是,python会在最后一次操作时自动将dtype转换为boolean.我怎么能阻止这个?
jez*_*ael 17
如果需要替换boolean值True和False:
booleandf = pandasDF.select_dtypes(include=[bool])
booleanDictionary = {True: 'TRUE', False: 'FALSE'}
for column in booleandf:
pandasDF[column] = pandasDF[column].map(booleanDictionary)
Run Code Online (Sandbox Code Playgroud)
样品:
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
Run Code Online (Sandbox Code Playgroud)
编辑:
与Simplier解决方案replace通过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
Run Code Online (Sandbox Code Playgroud)