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 pddata = {'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 dob0 Ben 1982-07-08 00:00:001 Anna 1987-03-01 00:00:002 Zoe 2016-02-12 00:00:003 Tom 2002-08-14 00:00:004 John 2011-01-19 00:00:005 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-081 1987-03-012 2016-02-123 2002-08-144 2011-01-195 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 371 332 43 174 95 4
