计算每个连续周期的天数 pandas

Count number of days in each continuous period pandas

假设我有下一个 df N03_zerodate_code 已经是 datetime):

item_code       date_code
8028558104973   2022-01-01
8028558104973   2022-01-02
8028558104973   2022-01-03
8028558104973   2022-01-06
8028558104973   2022-01-07
7622300443269   2022-01-01
7622300443269   2022-01-10
7622300443269   2022-01-11
513082          2022-01-01
513082          2022-01-02
513082          2022-01-03

数百万行 date_code 分配给了一些 item_code。 我正在尝试获取每个 item_code 的每个连续周期的天数,所有其他类似问题对我没有帮助。 预期的 df 应该是:

item_code       continuous_days
8028558104973   3
8028558104973   2
7622300443269   1
7622300443269   2
513082          3

一旦天数顺序中断,它应该按照这个顺序计算天数,然后重新开始计算。 目的是,然后能够为每个 item_code.

获得具有 countminmaxmean 的数据帧

像这样:

item_code       no. periods   min   max   mean
8028558104973   2             2     3     2.5
7622300443269   2             1     2     1.5
513082          1             3     3     3

有什么建议吗?

连续几天比较差异 Series.diff in days by Series.dt.days for not equal 1 by Series.ne with cumulative sum by Series.cumsum and then use GroupBy.size, remove second level by DataFrame.droplevel 并创建 DataFrame:

df['date_code'] = pd.to_datetime(df['date_code'])

df1= (df.groupby(['item_code',df['date_code'].diff().dt.days.ne(1).cumsum()], sort=False)
        .size()
        .droplevel(1)
        .reset_index(name='continuous_days'))
print (df1)
       item_code  continuous_days
0  8028558104973                3
1  8028558104973                2
2  7622300443269                1
3  7622300443269                2
4         513082                3

然后通过 GroupBy.agg:

的命名聚合来聚合值
df2 = (df1.groupby('item_code', sort=False, as_index=False)
          .agg(**{'no. periods': ('continuous_days','size'),
                 'min':('continuous_days','min'),
                 'max':('continuous_days','max'),
                 'mean':('continuous_days','mean')}))
print (df2)
       item_code  no. periods  min  max  mean
0  8028558104973            2    2    3   2.5
1  7622300443269            2    1    2   1.5
2         513082            1    3    3   3.0