pandas -两个日期之间的月数 [英] Pandas - Number of Months Between Two Dates

查看:180
本文介绍了 pandas -两个日期之间的月数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这应该很简单,但是我所看到的是涉及对数据框日期字段进行迭代以确定两个日期之间的差异的技术.而且我遇到了麻烦.我熟悉MSSQL DATEDIFF,所以我认为Pandas日期时间会有类似的东西.我也许可以,但是我很想念它.

I think this should be simple but what I've seen are techniques that involve iterating over a dataframe date fields to determine the diff between two dates. And I'm having trouble with it. I'm familiar with MSSQL DATEDIFF so I thought Pandas datetime would have something similar. I perhaps it does but I'm missing it.

是否有Pandonic的方法可以将月份数确定为两个日期(日期时间)之间的整数,而无需进行迭代?请记住,可能存在数百万行,因此性能是一个考虑因素.

Is there a Pandonic way of determing the number of months as an integer between two dates (datetime) without the need to iterate? Keeping in mind that there potentially are millions of rows so performance is a consideration.

日期是日期时间对象,结果是这样的-新列为Month:

The dates are datetime objects and the result would like this - new column being Month:

Date1           Date2         Months
2016-04-07      2017-02-01    11
2017-02-01      2017-03-05    1

推荐答案

我的朋友,这是一个非常简单的答案:

Here is a very simple answer my friend:

df['nb_months'] = ((df.date2 - df.date1)/np.timedelta64(1, 'M'))

现在:

df['nb_months'] = df['nb_months'].astype(int)

这篇关于 pandas -两个日期之间的月数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆