python/pandas发现两个日期之间的年数

2024-05-16 05:58:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个pandas数据框,其中有两列包含日期。我想知道这两个日期之间的年数,同时计算闰年。

理想的解决方案是假定一年总有一定的天数。因为岁月并不总是有365天。

样本数据:

date_end    date_start
2010-02-09  1933-03-03
2010-03-19  1924-04-08
2010-04-19  1924-04-08
2010-09-06  1924-04-08
2010-09-24  1924-04-08
2010-01-09  1933-04-29
2010-02-26  1933-04-29
2010-01-31  1953-06-10
2010-07-07  1928-11-14
2010-12-01  1974-11-17

date_startdate_end属于“datetime”数据类型。我想要一个新的专栏,这是两个日期之间的年数。很容易得到这两个日期之间的天数(df['diff'] = df.date_end - df.date_start),但随后我遇到了麻烦,因为给定天数的年数取决于“何时”发生,因为闰年。

这类似于一个人的年龄。我试过用一些方法来解决类似的问题,但很多问题都是关于两次约会之间的天数或周数。我已经有了一种不计算闰年的方法来计算年数,但我想更准确一些。


Tags: 数据方法pandasdfdatetimedate解决方案start
1条回答
网友
1楼 · 发布于 2024-05-16 05:58:09

假设要将一年定义为365天,则可以执行以下操作:

>> df
    date_end date_start  is_leapyear
0 2016-02-28 2015-02-28            0
1 2017-02-28 2016-02-28            1
2 2018-02-28 2017-02-28            0

>> df['diff_in_days'] = df['date_end'] - df['date_start']
>> df['diff_in_years'] = df["diff_in_days"] / timedelta(days=365)
>> print df[["date_end", "date_start", "diff_in_years"]]

>> df
    date_end date_start  is_leapyear  diff_in_years
0 2016-02-28 2015-02-28            0        1.00000
1 2017-02-28 2016-02-28            1        1.00274
2 2018-02-28 2017-02-28            0        1.00000

如你所见,在有额外天数的年份(2月29日),两个日期之间的间隔时间更长。在你的情况下,这将是:

    date_end date_start  diff_in_years
0 2010-02-09 1933-03-03      76.991781
1 2010-03-19 1924-04-08      86.002740
2 2010-04-19 1924-04-08      86.087671
3 2010-09-06 1924-04-08      86.471233
4 2010-09-24 1924-04-08      86.520548
5 2010-01-09 1933-04-29      76.750685
6 2010-02-26 1933-04-29      76.882192
7 2010-01-31 1953-06-10      56.682192
8 2010-07-07 1928-11-14      81.698630
9 2010-12-01 1974-11-17      36.063014

另一方面,如果你只是想在不同的年份。i、 e.减去发生日期的年份(不包括发生日期的年份)。然后你可以这样做:

df['date_end_year'] = df.date_end.apply(lambda x: x.year)
df['date_start_year'] = df.date_start.apply(lambda x: x.year)
df['diff_in_years'] = df['date_end_year'] - df['date_start_year']
print df[["date_end", "date_start", "diff_in_years"]]

    date_end date_start  diff_in_years
0 2016-02-28 2015-02-28              1
1 2017-02-28 2016-02-28              1
2 2018-02-28 2017-02-28              1

在你的情况下,这将是:

    date_end date_start  diff_in_years
0 2010-02-09 1933-03-03             77
1 2010-03-19 1924-04-08             86
2 2010-04-19 1924-04-08             86
3 2010-09-06 1924-04-08             86
4 2010-09-24 1924-04-08             86
5 2010-01-09 1933-04-29             77
6 2010-02-26 1933-04-29             77
7 2010-01-31 1953-06-10             57
8 2010-07-07 1928-11-14             82
9 2010-12-01 1974-11-17             36

相关问题 更多 >