如何找出年份中两个日期之间的差异

时间:2018-12-08 16:30:42

标签: python pandas python-datetime

我在数据框中有两列已转换为日期时间。我正在尝试减去这些数字,并找出年份之间的差异。这是我正在使用的代码:

from dateutil.relativedelta import relativedelta
difference_in_years = relativedelta(x['start'], x['end']).year

但是,我收到以下错误消息:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

出了什么问题?

4 个答案:

答案 0 :(得分:2)

将属性.yearsapplyaxis=1一起用于按行处理:

df = pd.DataFrame({'start':['2015-10-02','2014-11-05'],
                   'end':['2018-01-02','2018-10-05']})

df['start'] = pd.to_datetime(df['start'])
df['end'] = pd.to_datetime(df['end'])

from dateutil.relativedelta import relativedelta

df['y'] = df.apply(lambda x: relativedelta(x['end'], x['start']).years, axis=1)

或使用list comprehension

df['y'] = [relativedelta(i, j).years for i, j in zip(df['end'], df['start'])]

print (df)
       start        end  y
0 2015-10-02 2018-01-02  2
1 2014-11-05 2018-10-05  3

编辑:

df = pd.DataFrame({'start':['2015-10-02','2014-11-05'],
                   'end':['2018-01-02',np.nan]})

df['start'] = pd.to_datetime(df['start'])
df['end'] = pd.to_datetime(df['end'])

from dateutil.relativedelta import relativedelta

m = df[['start','end']].notnull().all(axis=1)
df.loc[m, 'y'] = df[m].apply(lambda x: relativedelta(x['end'], x['start']).years, axis=1)
print (df)
       start        end    y
0 2015-10-02 2018-01-02  2.0
1 2014-11-05        NaT  NaN

答案 1 :(得分:1)

检查此答案calculate the difference between two datetime.date() dates in years and months

from dateutil import relativedelta as rdelta
from datetime import date
d1 = date(2001,5,1)
d2 = date(2012,1,1)
rd = rdelta.relativedelta(d2,d1)
rd
relativedelta(years=+10, months=+8)

答案 2 :(得分:0)

您可以通过

(df['end'] - df['start'])/pd.Timedelta(1, 'Y')

并根据需要四舍五入结果。

在大熊猫v0.23.4中,以后可以做

(df['end'] - df['start'])//pd.Timedelta(1, 'Y')

立即获得全年差异。

答案 3 :(得分:0)

您可以将timedelta系列除以年份单位,并在必要时四舍五入:

# data from jezrael

df['years'] = (df['end'] - df['start']) / np.timedelta64(1, 'Y')
df['years_floor'] = df['years'].round()

print(df)

       start        end     years  years_floor
0 2015-10-02 2018-01-02  2.253297          2.0
1 2014-11-05        NaT       NaN          NaN