减去时间并以年为单位输出,四舍五入到两位小数

Subtracting time and having output in years, rounded to two decimals

我有一个包含客户生日的数据集,我希望将该变量转换为以年为单位的年龄,四舍五入到小数点后两位或三位。我想出了如何将整个列转换为时间戳。

一个问题是我不知道这些数据有多旧,但它是在 2019 年 4 月 4 日发布到网站上的,所以我将那一天用作 "today"计算时间增量。

当我尝试减去这两个日期时,差异以天为单位。

这是我所拥有的和 TIA 的任何帮助:

数据以出生日期开头,格式为日-月-年,即:30-12-1993

## Making sure all observations are in same format
training_df['DATE_OF_BIRTH'] = pd.to_datetime(training_df['DATE_OF_BIRTH'])


## Checking format of an individual DOB
training_df['DATE_OF_BIRTH'][0]

Out[121]:
Timestamp('1984-01-01 00:00:00')


## Setting "today" as 4-4-2019
data_time_reference=datetime(2019, 4, 4)

data_time_reference

Out[155]:
datetime.datetime(2019, 4, 4, 0, 0)


## Subtracting
data_time_reference - training_df['DATE_OF_BIRTH'][0]

输出为

Timedelta('12877 days 00:00:00')

当我需要它是 35.26(即 12,877 除以 365.25)

数据在Kaggle.com:https://www.kaggle.com/avikpaul4u/vehicle-loan-default-prediction

考虑以下数据框:

  DATE_OF_BIRTH
0    01-01-1984
1    30-12-1993
2    02-12-1997
3    04-07-1963
4    14-04-2000
#Convert the values in dates column to datetime object
df['DATE_OF_BIRTH'] = pd.to_datetime(df['DATE_OF_BIRTH'])

#Set the reference date to subtract
data_time_reference= datetime(2019, 4, 4)

#Get the no of days (integer) after subtracting from reference date
df['days_int'] = pd.to_numeric((data_time_reference - df['DATE_OF_BIRTH']).dt.days, downcast='integer')

print(df)

现在,它看起来像这样:

  DATE_OF_BIRTH  days_int
0    1984-01-01     12877
1    1993-12-30      9226
2    1997-02-12      8086
3    1963-04-07     20451
4    2000-04-14      6929

然后,将 days_int 列除以 365.25 并四舍五入到小数点后两位。

df['result'] = (df['days_int']/365.25).round(2)

最终输出:

  DATE_OF_BIRTH  days_int  result
0    1984-01-01     12877   35.26
1    1993-12-30      9226   25.26
2    1997-02-12      8086   22.14
3    1963-04-07     20451   55.99
4    2000-04-14      6929   18.97