简体   繁体   中英

How can I convert a pandas dataframe column with birth year to age? (e.g. '1991' -> 28)

I have a pandas dateframe, with one column called 'Age'. There are several thousands of birth years there (1970, 1953, 2018 etc).

How can I convert that year into an approximate age? For example if the year was "1991" I would want it to show "28" instead.

I have tried playing around a bit with datetime, but without success.

df_age.head()

1970
1953
1953
1977
2017
Name: Age, dtype: int64

You can easily subtract the birth year from current year to get age.

To get current year using pandas you can do

pd.Timestamp('now').year

Hence you can do,

df['Age'] = pd.Timestamp('now').year - df['Age'] 

to get the Age . Keep in mind that this will over-ride the column value. If you don't want that, assign the result to some other column.

from datetime import date 

def calculateAge(birthDate): 
    today = date.today() 
    age = today.year - birthDate.year - 
         ((today.month, today.day) < 
         (birthDate.month, birthDate.day)) 

    return age 

print(calculateAge(date(1997, 2, 3)), "years") 

OR

from datetime import date 

def calculateAge(birthDate): 
    days_in_year = 365.2425    
    age = int((date.today() - birthDate).days / days_in_year) 
    return age 

print(calculateAge(date(1997, 2, 3)), "years")

If you want help doing it with dataframe. Comment so, but this is are 2 ways we can do it.

This is the answer you are looking for.

from datetime import date 
import pandas as pd
import datetime
def calculateAge(birthDate):
    today = str(datetime.date.today());
    curr_year = int(today[:4]); 
    age = curr_year-birthDate 

    return age 



lst=['1997','1998']
df=pd.DataFrame(lst)
df[0]=df[0].astype(int)
df['age']=np.nan
df['age']=df[0].apply(calculateAge)

Output-

   0  age
0  1997   22
1  1998   21

You don't need datetime, you just need to subtract the birth year from the current year. 2019 - 1991 = 28 for example.

The proposed solution df['Age'] = pd.Timestamp('now').year - df['Age'] is certainly one quick way to do it. There are other ways that would work too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM