首页 > 解决方案 > Python dataframe group by index level rather than index names

问题描述

I'm having a multi-indexed dataframe. I understand that groupby(level=0) means groupby the first index, then how can I group the data by the first two indices using this method?
I tried groupby(level=0 and 1), and it did not work.

标签: pythonpandasdataframe

解决方案


Use list like:

df.groupby(level=[0,1])

Also if want use aggregate function like sum, mean, max, min:

df.groupby(level=[0,1]).sum()

is possible simplify to:

df.sum(level=[0,1])

推荐阅读