python-3.x - 在 groupby 之后对同一列应用多个操作
问题描述
我有以下df
,
id year_month amount
10 201901 10
10 201901 20
10 201901 30
20 201902 40
20 201902 20
我想groupby
id
然后year-month
得到组大小和总和amount
,
df.groupby(['id', 'year_month'], as_index=False)['amount'].sum()
df.groupby(['id', 'year_month'], as_index=False).size().reset_index(name='count')
我想知道如何在一行中同时进行;
id year_month amount count
10 201901 60 3
20 201902 60 2
解决方案
使用agg
:
df.groupby(['id', 'year_month']).agg({'amount': ['count', 'sum']})
amount
count sum
id year_month
10 201901 3 60
20 201902 2 60
如果要删除多索引,请使用MultiIndex.droplevel
:
s = df.groupby(['id', 'year_month']).agg({'amount': ['count', 'sum']}).rename(columns ={'sum': 'amount'})
s.columns = s.columns.droplevel(level=0)
s.reset_index()
id year_month count amount
0 10 201901 3 60
1 20 201902 2 60
推荐阅读
- sql-server - 来自 sys.sysusers 的查询仅返回部分记录
- angular - 通过其他 div 的 ngIf 生成一些 div
- java - JAVA JSON 保存文件
- android - Firestore 应用程序在调试中工作,但签名的 apk 给出错误
- hadoop - 成功的任务在尝试提交时生成 mapreduce.counters.LimitExceededException
- ios - 将背景设置为透明后的iOS UINavigationController显示黑屏
- azure - Cosmos DB 存储过程在没有 PartitionKey 的情况下无法执行
- python - Openpyxl: unexpected fail with CellIsRule function
- java - 引起:android.database.sqlite.SQLiteException:没有这样的表:食物(代码1 SQLITE_ERROR):,编译时:SELECT * FROM food order by id asc 1
- c# - TreeView 多个父级