map multiple columns by a single dictionary in pandas

mapping, pandas, python

Solution

You could use a `stack`/`unstack` idiom

df.stack().map(dict_map_yn_bool).unstack()

Using @jezrael's setup

df = pd.DataFrame({'nearby_subway_station':['yes','no'], 'Station':['no','yes']})
dict_map_yn_bool={'yes':True, 'no':False}

Then

df.stack().map(dict_map_yn_bool).unstack()

  Station nearby_subway_station
0   False                  True
1    True                 False

timing small data

bigger data

Problem

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?

Original source