Years between two date column = 'Timedelta' object has no attribute 'item'

不羁的心 提交于 2019-12-01 09:15:15

I think you need sub for subtract, convert timedeltas to days by dt.days, divide by div and last round:

df_Years['Year_To_Maturity'] = (df_Years['maturity_date'].sub(df_Years['Today'])
                                                         .dt.days
                                                         .div(365)
                                                         .round(4))
print (df_Years)
  maturity_date      Today  Year_To_Maturity
0    2022-12-15 2018-03-21            4.7397
1    2028-02-15 2018-03-21            9.9123
2    2045-12-01 2018-03-21           27.7178
3    2025-08-18 2018-03-21            7.4164
4    2019-01-16 2018-03-21            0.8247
5    2018-12-21 2018-03-21            0.7534

Thanks @pir for better solution:

df_Years['Year_To_Maturity'] = (df_Years['maturity_date'].sub(df_Years['Today'])
                                                         .dt.days
                                                         .div(365.25)
                                                         .round(4))
print (df_Years)
  maturity_date      Today  Year_To_Maturity
0    2022-12-15 2018-03-21            4.7365
1    2028-02-15 2018-03-21            9.9055
2    2045-12-01 2018-03-21           27.6988
3    2025-08-18 2018-03-21            7.4114
4    2019-01-16 2018-03-21            0.8241
5    2018-12-21 2018-03-21            0.7529
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!