社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

b00kgrrl • 5 年前 • 1585 次点击  

我有我按摩过的数据看起来像这样。

         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

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/34359
 
1585 次点击  
文章 [ 1 ]  |  最新文章 5 年前
anky_91
Reply   •   1 楼
anky_91    5 年前

Date 列到 datetime :

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)

   Date  cum_Amount
0     9    32029.59
1    10    31063.64
2    11    32596.70
3    12    30630.96

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

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