How to convert a dataframe column of date of birth DOB to column of age with pandas in python ?

How to convert a dataframe column of date of birth DOB to column of age with pandas in python ?

Daidalos June 17, 2020


Examples of how to convert a dataframe column of date of birth DOB to column of age with pandas in python:

1 -- Create a dataframe

Lets consider the following dataframe for example

import pandas as pd

data = {'Name':['Ben','Anna','Zoe','Tom','John','Steve'], 
        'dob':['1982-07-08 00:00:00',
               '1987-03-01 00:00:00',
               '2016-02-12 00:00:00',
               '2002-08-14 00:00:00',
               '2011-01-19 00:00:00',
               '2016-03-22 00:00:00']}

df = pd.DataFrame(data)

returns

print(df)

    Name                  dob
0    Ben  1982-07-08 00:00:00
1   Anna  1987-03-01 00:00:00
2    Zoe  2016-02-12 00:00:00
3    Tom  2002-08-14 00:00:00
4   John  2011-01-19 00:00:00
5  Steve  2016-03-22 00:00:00

2 -- Convert DOB to datetime

First it is necessary to convert dob to datetime using the pandas function to_datetime():

df['Date'] = pd.to_datetime(df.dob)

df['Date']

returns

0   1982-07-08
1   1987-03-01
2   2016-02-12
3   2002-08-14
4   2011-01-19
5   2016-03-22

3 -- Get the age from the DOB

Create a function that returns the age from the DOB:

def from_dob_to_age(born):
    today = datetime.date.today()
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day))

Apply the function to the column date

df['Date'].apply(lambda x: from_dob_to_age(x))

0    37
1    33
2     4
3    17
4     9
5     4

4 -- References