通过 pandas 中的单个字典映射多列 [英] map multiple columns by a single dictionary in pandas
本文介绍了通过 pandas 中的单个字典映射多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个DataFrame,其中有多个带有'yes'和'no'字符串的列.我希望所有这些都转换为布尔型dtype.要映射一列,我将使用
I have a DataFrame with a multiple columns with 'yes' and 'no' strings. I want all of them to convert to a boolian dtype. To map one column, I would use
dict_map_yn_bool={'yes':True, 'no':False}
df['nearby_subway_station'].map(dict_map_yn_bool)
这将完成一栏的工作.如何用单行代码替换多列?
This would do the job for the one column. how can I replace multiple columns with single line of code?
推荐答案
您可以使用 stack
/ unstack
习惯用法
df.stack().map(dict_map_yn_bool).unstack()
使用@jezrael的设置
Using @jezrael's setup
df = pd.DataFrame({'nearby_subway_station':['yes','no'], 'Station':['no','yes']})
dict_map_yn_bool={'yes':True, 'no':False}
然后
df.stack().map(dict_map_yn_bool).unstack()
Station nearby_subway_station
0 False True
1 True False
定时
小数据
更大的数据
这篇关于通过 pandas 中的单个字典映射多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文