gpt4 book ai didi

python - 减去时间并得到以年为单位的输出,四舍五入到小数点后两位

转载 作者:行者123 更新时间:2023-12-01 07:00:08 25 4
gpt4 key购买 nike

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

一个问题是我不知道数据有多久了,但它是在 2019 年 4 月 4 日发布到网站上的,所以我使用那天作为“今天”来计算时间增量。

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

以下是我所拥有的信息以及 TIA 的帮助信息:

数据以 DOB 开头,采用日-月-年格式,即: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

关于python - 减去时间并得到以年为单位的输出,四舍五入到小数点后两位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58676015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com