Pandas get the age from a date (example: date of birth)

后端 未结 6 1191
夕颜
夕颜 2020-12-01 06:33

How can I calculate the age of a person (based off the dob column) and add a column to the dataframe with the new value?

dataframe looks like the following:

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-01 07:27

    I found easier solution:

        import pandas as pd
        from datetime import datetime
        from datetime import date
    
        d = {'col0': [1, 2, 6], 
             'col1': [3, 8, 3], 
             'col2': ['17.02.1979', '11.11.1993', '01.08.1961']}
    
        df = pd.DataFrame(data=d)
    
        def calculate_age(born):
            born = datetime.strptime(born, "%d.%m.%Y").date()
            today = date.today()
            return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
    
        df['age'] = df['col6'].apply(calculate_age)
        print(df)
    

    output:

         col0  col1  col3        age
    0       1     3  17.02.1979   39
    1       2     8  11.11.1993   24
    2       6     3  01.08.1961   57
    

提交回复
热议问题