本文介绍了我如何获得 pandas 的年龄和日期的年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的数据
Customer_id Date-of-birth
1 1992-07-02
2 1991-07-03
这是我的代码
import datetime as dt
df['now'] = dt.datetime.now()
df['age'] = df['now'].dt.date - df['Date-of-birth']
这是结果
Customer_id Date-of-birth age
1 1992-07-02 xxxx days
2 1991-07-03 xxxx days
我想要的结果是
Customer_id Date-of-birth age
1 1992-07-02 26 years 22 days
2 1991-07-03 27 years 21 days
现在让我们根据 df.dtypes
,出生日期
是一个对象,因为它基于下拉菜单中的客户输入
Just let you now, by df.dtypes
, Date-of-birth
is an object because is based on customer input in dropdown
我该如何实现?我希望这个问题足够清楚
How can I achieve this? I hope the question is clear enough
推荐答案
将此解决方案与自定义功能一起使用,因为计算它是不容易,因为leap年:
Use this solution with custom function, because count it is not easy because leaps years:
from dateutil.relativedelta import relativedelta
def f(end):
r = relativedelta(pd.to_datetime('now'), end)
return '{} years {} days'.format(r.years, r.days)
df['age'] = df["Date-of-birth"].apply(f)
print (df)
Customer_id Date-of-birth age
0 1 1992-07-02 26 years 22 days
1 2 1991-07-03 27 years 21 days
这篇关于我如何获得 pandas 的年龄和日期的年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!