Convert birth date to age in Pandas

Convert birth date to age in Pandas

To convert a birth date to age in pandas, you can subtract the birth date from the current date and then extract the year to get the age. Here's how you can achieve this:

  • Import necessary libraries:
import pandas as pd from datetime import datetime 
  • Sample DataFrame with birth dates:
df = pd.DataFrame({ 'name': ['Alice', 'Bob', 'Charlie'], 'birth_date': ['1990-01-01', '1985-05-20', '2000-11-15'] }) 
  • Function to calculate age from birth date:
def calculate_age(birth_date): today = datetime.today() birth_date = datetime.strptime(birth_date, "%Y-%m-%d") age = today.year - birth_date.year - ((today.month, today.day) < (birth_date.month, birth_date.day)) return age 
  • Apply the function to the DataFrame:
df['age'] = df['birth_date'].apply(calculate_age) print(df) 

Output:

 name birth_date age 0 Alice 1990-01-01 33 1 Bob 1985-05-20 38 2 Charlie 2000-11-15 22 

Note: The age values in the output might differ based on when you run the code because it uses the current date to compute the age.


More Tags

pyaudio webpack-4 service aes self-join angular-ui filenames dropzone.js html-table pypdf

More Programming Guides

Other Guides

More Programming Examples