大熊猫月份差异

问题描述 投票:0回答:2

我有一个数据框日期列具有以下值

2015-01-01
2015-02-01
2015-03-01
2015-07-01
2015-08-01
2015-10-01
2015-11-01
2016-02-01

我希望在几个月内找到这些值的差异,如下所示

  date_dt       diff_mnts
2015-01-01        0
2015-02-01        1
2015-03-01        1
2015-07-01        4 
2015-08-01        1
2015-10-01        2
2015-11-01        1
2016-02-01        3

我试图使用diff()方法计算天数,然后转换为astype('timedelta64(M)')。但在这些情况下,当天数小于30时 - 它显示的月差值为0.请告诉我,如果有任何简单的内置功能,我可以尝试在这种情况下。

python pandas date dataframe
2个回答
3
投票

选项1 更改期间并致电diff

df    
        Date
0 2015-01-01
1 2015-02-01
2 2015-03-01
3 2015-07-01
4 2015-08-01
5 2015-10-01
6 2015-11-01
7 2016-02-01

df.Date.dtype
dtype('<M8[ns]')
df.Date.dt.to_period('M').diff().fillna(0)

0    0
1    1
2    1
3    4
4    1
5    2
6    1
7    3
Name: Date, dtype: int64

选项2 或者,在diff上调用dt.month,但是你需要考虑一年内的差距(由于@galaxyan,解决方案有所改善!) -

i = df.Date.dt.year.diff() * 12 
j = df.Date.dt.month.diff()

(i + j).fillna(0).astype(int)

0    0
1    1
2    1
3    4
4    1
5    2
6    1
7    3
Name: Date, dtype: int64

警告(感谢发现它)是这对于一年多的差距不起作用。


-1
投票

请尝试以下步骤

  • 将列转换为datetime格式。
  • 使用.month方法获取月份编号
  • 在pandas中使用shift()方法来计算差异

示例代码看起来像这样

df['diff_mnts'] = date_dt.month - date_dt.shift().month
© www.soinside.com 2019 - 2024. All rights reserved.