Python groupby、cumsum和max用于计算月末余额

Python groupby、cumsum和max用于计算月末余额,python,pandas,Python,Pandas,我有数据,我已经按摩看起来像这样 Date Amount Month Balance 0 9/4/2018 32000.00 9 32000.00 1 9/30/2018 29.59 9 32029.59 2 10/1/2018 34.05 10 32063.64 3 10/31/2018 -1000.00 10 31063.64 4 11/1/2018 1500.00 11 32

我有数据,我已经按摩看起来像这样

         Date    Amount Month   Balance
0    9/4/2018  32000.00     9  32000.00
1   9/30/2018     29.59     9  32029.59
2   10/1/2018     34.05    10  32063.64
3  10/31/2018  -1000.00    10  31063.64
4   11/1/2018   1500.00    11  32563.64
5  11/30/2018     33.06    11  32596.70
6   12/1/2018  -2000.00    12  30596.70
7  12/31/2018     34.26    12  30630.96
我需要计算每个月底的余额和最高的月末余额。我尝试过groupby、cumsum和max的各种组合,但没有达到预期效果

以下是我到目前为止的情况:

month_end_balance = yearly_df.groupby('Month')['Amount'].cumsum()
max_month_end_balance = month_end_balance.max()
我预计月末余额为:

9   32029.59
10  31063.64
11  32596.70
12  30630.96

我预计最大月底余额为32596.70

首先将
日期
列转换为
日期时间

df.Date=pd.to_datetime(df.Date,format='%m/%d/%Y')
然后:

m=(df.assign(cum_Amount=df.Amount.cumsum()).
  groupby(df.Date.dt.month)['cum_Amount'].max().reset_index())
print(m)

编辑似乎您已经有余额,您只想过滤月末日期,请使用:

from pandas.tseries.offsets import MonthEnd
df[df.Date.eq(df.Date+MonthEnd(0))]


我怀疑您只是想要
sum
,而不是
cumsum
。当我运行此代码时,我得到了一个不正确的10月月末余额值(32063.64)@b00kgrrl您能检查编辑部分并确认吗?谢谢
from pandas.tseries.offsets import MonthEnd
df[df.Date.eq(df.Date+MonthEnd(0))]
        Date   Amount  Month   Balance
1 2018-09-30    29.59      9  32029.59
3 2018-10-31 -1000.00     10  31063.64
5 2018-11-30    33.06     11  32596.70
7 2018-12-31    34.26     12  30630.96