繁体   English   中英

如何将出生年份的熊猫数据框列转换为年龄? (例如'1991'-> 28)

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

我有一个熊猫日期框架,其中一栏名为“年龄”。 那里有数千个出生年份(1970、1953、2018等)。

我该如何将那一年转换成大致年龄? 例如,如果年份为“ 1991”,我希望它显示为“ 28”。

我尝试过与日期时间一起玩,但是没有成功。

df_age.head()

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

您可以轻松地从当前年份中减去出生年份来获得年龄。

要获得使用熊猫的当前年份,您可以执行

pd.Timestamp('now').year

因此,您可以做,

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

获得Age 请记住,这将覆盖列值。 如果您不希望这样做,请将结果分配给其他列。

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") 

要么

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")

如果您需要帮助,请使用数据框。 发表评论,但这是我们可以通过的两种方式。

这就是您要寻找的答案。

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)

输出-

   0  age
0  1997   22
1  1998   21

您不需要日期时间,只需从当前年份中减去出生年份。 例如,2019年-1991年= 28。

提议的解决方案df['Age'] = pd.Timestamp('now').year - df['Age']当然是一种快速的解决方法。 还有其他可行的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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