David Stansby
David Stansby

Reputation: 1911

Finding minimum value for each level of a multi-index dataframe

I have a DataFrame that looks like this:

        data
a   b
1   1   0.1
    2   0.2
    3   0.3
2   1   0.5
    2   0.6
    3   0.7

and I want to find the minimum value for each level of a ignoring the b level, so as an output I'm looking for something like

a   min
1   0.1
2   0.5

Upvotes: 6

Views: 4301

Answers (1)

jezrael
jezrael

Reputation: 862661

The simpliest is use min with parameter level=0:

print (df.data.min(level=0).reset_index(name='min'))
   a  min
0  1  0.1
1  2  0.5

If need output as df and only one column df:

print (df.min(level=0))
   data
a      
1   0.1
2   0.5

Or groupby by first level with aggregating min:

print (df.groupby(level=0).data.min().reset_index(name='min'))
   a  min
0  1  0.1
1  2  0.5

Upvotes: 7

Related Questions