Python calculate age from date of birth dataframe

To calculate the age from a date of birth in a dataframe using Python, you can follow these steps:

  1. Import the necessary libraries: pandas, datetime.
  2. Create a pandas DataFrame that contains the date of birth column.
  3. Convert the date of birth column to a datetime datatype using pd.to_datetime() function.
  4. Get the current date using the datetime library’s datetime.today() method.
  5. Subtract the date of birth column from the current date to get the age difference.

Here’s an example to illustrate the process:

# Import libraries
import pandas as pd
from datetime import datetime

# Create a DataFrame with date of birth column
data = {'dob': ['1990-01-01', '1985-05-10', '2000-08-20']}
df = pd.DataFrame(data)

# Convert dob column to datetime datatype
df['dob'] = pd.to_datetime(df['dob'])

# Get current date
current_date = datetime.today().date()

# Calculate age
df['age'] = (current_date - df['dob']).astype('timedelta64[Y]')

print(df)

Output:

         dob   age
0 1990-01-01  31.0
1 1985-05-10  36.0
2 2000-08-20  21.0

Leave a comment