Remap values in pandas column with a dict

后端 未结 10 1122
囚心锁ツ
囚心锁ツ 2020-11-21 05:14

I have a dictionary which looks like this: di = {1: \"A\", 2: \"B\"}

I would like to apply it to the \"col1\" column of a dataframe similar to:

10条回答
  •  旧时难觅i
    2020-11-21 05:28

    Given map is faster than replace (@JohnE's solution) you need to be careful with Non-Exhaustive mappings where you intend to map specific values to NaN. The proper method in this case requires that you mask the Series when you .fillna, else you undo the mapping to NaN.

    import pandas as pd
    import numpy as np
    
    d = {'m': 'Male', 'f': 'Female', 'missing': np.NaN}
    df = pd.DataFrame({'gender': ['m', 'f', 'missing', 'Male', 'U']})
    

    keep_nan = [k for k,v in d.items() if pd.isnull(v)]
    s = df['gender']
    
    df['mapped'] = s.map(d).fillna(s.mask(s.isin(keep_nan)))
    

        gender  mapped
    0        m    Male
    1        f  Female
    2  missing     NaN
    3     Male    Male
    4        U       U
    

提交回复
热议问题