map multiple columns by a single dictionary in pandas

前端 未结 3 667
轻奢々
轻奢々 2021-01-03 04:06

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

         


        
3条回答
  •  猫巷女王i
    2021-01-03 04:48

    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

提交回复
热议问题