Izaskun Mendia
Izaskun Mendia

Reputation: 105

Get first index from multiindex grouping by level

I have a multiindex pandas dataframe:

                              SHOPPING_COUNT  
CLIENT          YEAR MONTH               
1000063         2013 12             9  
                2014 1              9  
                     2              7  
                     3              9  
                2015 4              6  
                     5              5  
                     6              9  
1001327         2014 5              1  
                     6              1  
                2015 2              7  
                     3              1  
                     4              3 
1001399         2013 8              1 

And I would to know the first index of each client, ordering by level 0. I mean, I would want to get:

1000063         2013 12
1001327         2014 5
1001399         2013 8              

Upvotes: 4

Views: 2025

Answers (2)

IanS
IanS

Reputation: 16241

It's not very programmatic, but if you look at the result of:

client = 1000063
df.loc[client].index

Then the following would work:

year  = df.loc[client].index.levels[0][df.loc[client].index.labels[0][0]]
month = df.loc[client].index.levels[1][df.loc[client].index.labels[1][0]]

Upvotes: 1

Fabio Lamanna
Fabio Lamanna

Reputation: 21552

Let df be your dataframe, you can do something like:

df = df.groupby(level=0).apply(lambda x: x.iloc[0:1])
df.index = df.index.droplevel(0)

actually this should be more easy to do maybe, but I think that this method works.

Upvotes: 3

Related Questions