Replace column values using a dictionary

前端 未结 2 1628
暗喜
暗喜 2021-01-21 10:49

I have this dataframe where gender is expected to be male or female.

from io import StringIO
import pandas as pd

audit_trail = StringIO(\'\'\'
course_id Academi         


        
相关标签:
2条回答
  • 2021-01-21 11:19

    You can use:

    corrections={'mail':'male', 'maela':'male', 'maae':'male', 'male':'male', 'female':'female'}
    df11[['Gender']] = df11[['Gender']].applymap(corrections.get).fillna('other')
    print (df11)
       course_id  AcademicYear_to  months  TotalFee  Gender
    0        260             2017      24       100    male
    1        260             2018      12       140    male
    2        274             2016      36       300    male
    3        274             2017      24       340  female
    4        274             2018      12       200   other
    5        285             2017      24       300   other
    6        285             2018      12       200    male
    

    EDIT:

    For replace only one column is better cᴏʟᴅsᴘᴇᴇᴅ's answer. If want replace multiple columns, better is applymap.

    0 讨论(0)
  • 2021-01-21 11:34

    Add another two dummy entries to your corrections dict:

    corrections = {'male'   : 'male',    # dummy entry for male
                   'female' : 'female',  # dummy entry for female
                   'mail'   : 'male', 
                   'maela'  : 'male', 
                   'maae'   : 'male'}
    

    Now, use map and fillna:

    df11.Gender = df11.Gender.map(corrections).fillna('other')
    df11
    
       course_id  AcademicYear_to  months  TotalFee  Gender
    0        260             2017      24       100    male
    1        260             2018      12       140    male
    2        274             2016      36       300    male
    3        274             2017      24       340  female
    4        274             2018      12       200   other
    5        285             2017      24       300   other
    6        285             2018      12       200    male
    
    0 讨论(0)
提交回复
热议问题