[英]How do I get an age in years and date on pandas
Here's my data 这是我的数据
Customer_id Date-of-birth
1 1992-07-02
2 1991-07-03
Here's my code 这是我的代码
import datetime as dt
df['now'] = dt.datetime.now()
df['age'] = df['now'].dt.date - df['Date-of-birth']
Here's the result 这是结果
Customer_id Date-of-birth age
1 1992-07-02 xxxx days
2 1991-07-03 xxxx days
The result that I want is 我想要的结果是
Customer_id Date-of-birth age
1 1992-07-02 26 years 22 days
2 1991-07-03 27 years 21 days
Just let you now, by df.dtypes
, Date-of-birth
is an object because is based on customer input in dropdown 现在让我们通过
df.dtypes
, Date-of-birth
是一个对象,因为它是基于下拉列表中的客户输入
How can I achieve this? 我怎样才能做到这一点? I hope the question is clear enough
我希望这个问题足够清楚
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
Input: 输入:
import pandas as pd
import datetime as dt
now = dt.datetime.now()
for i in range(0, len(df)):
diff = now - dt.datetime.strptime(df['Date-of-Birth'][i], '%Y-%m-%d')
years = diff.days // 365
days = diff.days - (years*365)
df['age'][i] = str(years) + ' years ' + str(days) + ' days'
print(df)
Output: 输出:
Customer_id Date-of-Birth age
1 1992-07-04 26 years 25 days
2 1991-07-04 27 years 26 days
Maybe you could use something like the following. 也许你可以使用类似下面的东西。 Note that it relies on the fact that the average year has
365.25
days, so it may be a day off sometimes. 请注意,它依赖于平均年份为
365.25
天这一事实,因此有时可能会休息一天。
import datetime as dt
def year_days_diff(x):
diff = (dt.datetime.now() - x).days
return str(int(diff / 365.25)) + ' years ' + str(int(diff / 365.25 % 1 * 365.25)) + ' days'
Example: 例:
birth_date = dt.datetime.now() - dt.timedelta(10000)
year_days_diff(birth_date)
output: 输出:
'27 years 138 days'
This could give you age by rounding to years. 这可以通过四舍五入到年来给你年龄。
ref_date = dt.datetime.now()
df['age'] = df['Date-of-birth'].apply(lambda x: len(pd.date_range(start = x, end = ref_date, freq = 'Y')))
Use astype('<m8[Y]')
使用
astype('<m8[Y]')
Ex: 例如:
df['age'] = (pd.to_datetime('now') - df['Date-of-birth']).astype('<m8[Y]')
Demo: 演示:
import pandas as pd
df = pd.DataFrame({"Date-of-birth": pd.to_datetime(['1992-07-24', '1991-07-24'])})
df["age"] = (pd.to_datetime('now') - df["Date-of-birth"]).astype('<m8[Y]')
print(df)
Output: 输出:
Date-of-birth age
0 1992-07-24 25.0
1 1991-07-24 27.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.