NovaPoi
NovaPoi

Reputation: 73

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.

Upvotes: 1

Views: 40

Answers (1)

jezrael
jezrael

Reputation: 863226

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])

Upvotes: 1

Related Questions