假設你想一年定義爲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
另一方面,如果你只是想在年份的差異。即減去發生日期的年份(在該日發生的那一年發生的時間)。然後,你可以這樣做:
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
所以從1月 - 2016年1月 - 2017年爲一年。 2016年2月28日至2017年2月28日的情況如何?從2016年2月29日至2017年2月28日?從2016年2月29日至2017年3月1日?從2015年3月1日至2016年2月29日? – Boud
** 2016年2月28日至2017年2月28日:**一年零一天 ** 2016年2月29日至2017年2月28日:**一年? ** 2016年2月29日至2017年3月1日:**一年零一天? ** 2015年3月1日至2016年2月29日:** ...一年? 我對此很困惑,因爲它好像年代不是絕對測量,它們的長度取決於它是否是閏年。這就是爲什麼我希望熊貓(或其他一些軟件包)能夠爲我處理這個問題。 – user139188