Bryce93
Bryce93

Reputation: 481

Accessing row of multi-index DataFrame

Given a multi-index DataFrame:

df = pd.DataFrame({'Last Name' :  ['Deere','Deere','Foo'   ,'Foo'  ,'Man'   ],
                   'Middle Name': ['Goat' ,'Lamb' ,'Man'   ,'Man'  ,'Date'  ],
                   'First Name':  ['John' ,'Jane' ,'Group' ,'Alone','Karate'],
                   'Value1':      [ 1     , 2     , 3      , 4     , 5      ],
                   'Value2':      ['Green','Blue' ,'Yellow','Black','Purple']})

df.set_index(['Last Name','Middle Name','First Name'],inplace=True)

which looks like:

                                       Value1     Value2
Last Name   Middle Name   First Name
Deere       Goat          John         1          Green
            Lamb          Jane         2          Blue
Foo         Man           Group        3          Yellow
                          Alone        4          Black
Man         Date          Karate       5          Purple

I would like to access a specific row, using something along the lines of:

df.loc['Foo','Man','Alone']

and have that command return a Series that looks similar to:

Value1        4
Value2    Black
name: ('Last Name','Middle Name','First Name'), dtype: object

Upvotes: 0

Views: 3514

Answers (1)

Alexander
Alexander

Reputation: 109528

Your first method works fine:

s =  df.loc['Foo', 'Man', 'Alone']
>>> s
Value1        4
Value2    Black
Name: (Foo, Man, Alone), dtype: object

The only difference is that it appears you would like to rename the series.

s.name = tuple(df.index.names)

>>> s
Value1        4
Value2    Black
Name: (Last Name, Middle Name, First Name), dtype: object

Note that if you use double brackets, it returns a dataframe instead of a series.

>>> df.loc[[('Foo', 'Man', 'Alone')]]
                                  Value1 Value2
Last Name Middle Name First Name               
Foo       Man         Alone            4  Black

Upvotes: 1

Related Questions