【问题标题】:Group by month from a particular date python从特定日期python按月分组
【发布时间】:2020-06-25 21:05:52
【问题描述】:

我有一个包含日期、借方和贷方的帐户对帐单数据框。 假设工资是每月 20 日存入一次。

我想从每个月的 20 号开始对日期列进行分组,以查找借方和贷方的总和。例如,1 月 20 日至 2 月 20 日等等。

date_parsed Debit   Credit
0   2020-05-02  775.0   0.0
1   2020-04-30  209.0   0.0
2   2020-04-24  5000.0  0.0
3   2020-04-24  25000.0 0.0
... ... ... ...
79  2020-04-20  750.0   0.0
80  2020-04-15  5000.0  0.0
81  2020-04-13  0.0 2283.0
82  2020-04-09  0.0 6468.0
83  2020-04-03  0.0 1000.0

我不确定,但 pd.offsett 可以与 groupby 一起使用。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以添加一个额外的月份列,该列根据月份的日期向上或向下截断。然后它只是groupbysum。例如。 2020-06 月将包括 2020-05-20 和 2020-06-19 之间的日期。

    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({'date_parsed': ['2020-05-02', '2020-05-03', '2020-05-20', '2020-05-22'], 'Credit': [1,2,3,4], 'Debit': [5,6,7,8]})
    
    df['date'] = pd.to_datetime(df.date_parsed)
    df['month'] = np.where(df.date.dt.day < 20, df.date.dt.to_period('M'), (df.date + pd.DateOffset(months=1)).dt.to_period('M'))
    print(df[['month', 'Credit', 'Debit']].groupby('month').sum().reset_index())
    

    输入:

      date_parsed  Credit  Debit
    0  2020-05-02       1      5
    1  2020-05-03       2      6
    2  2020-05-20       3      7
    3  2020-05-22       4      8
    

    结果:

         month  Credit  Debit
    0  2020-05       3     11
    1  2020-06       7     15
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-05
      • 2018-02-11
      • 1970-01-01
      • 2017-12-08
      • 2012-02-03
      • 1970-01-01
      • 2018-08-30
      相关资源
      最近更新 更多