Alex T
Alex T

Reputation: 3754

Select by index value in multindex DF

I have DataFrame in this form, where place and source are indexes. How can I select by value in the place index?

               Count
place     source 
market  A         5
        D         4
        B         3
ecomm   A         7
        C         6
        B         4

I tried :

df_t[df_t.index.place=="market"]

But I got error.

This is desired result:

market      A         5
            D         4
            B         3

Upvotes: 3

Views: 40

Answers (1)

jezrael
jezrael

Reputation: 862591

If need market level in output use DataFrame.xs with drop_level parameter:

df1 = df_t.xs('market', drop_level=False)

Your solution is possible modify by Index.get_level_values:

df1 = df_t[df_t.index.get_level_values('place')=="market"]

print (df1)
               Count
place  source       
market A           5
       D           4
       B           3

If need remove this level, so no MultiIndex in output remove drop_level, because default value is drop_level = True or DataFrame.loc:

df2 = df_t.xs('market')

df2 = df_t.loc['market']

print (df2)
        Count
source       
A           5
D           4
B           3

Upvotes: 2

Related Questions