To calculate the age from a date of birth in a dataframe using Python, you can follow these steps:
- Import the necessary libraries: pandas, datetime.
- Create a pandas DataFrame that contains the date of birth column.
- Convert the date of birth column to a datetime datatype using pd.to_datetime() function.
- Get the current date using the datetime library’s datetime.today() method.
- 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
- Prepend-inner-icon vuetify
- Pydantic dynamic key
- Process is terminated due to stackoverflowexception. c#
- Property ‘initialprops’ not found on object of type ‘appdelegate *’
- Property ‘tobeinthedocument’ does not exist on type ‘jestmatchers
- Psycopg2.operationalerror: ssl error: decryption failed or bad record mac
- Python azure devops api