Skip to content
Advertisement

Find values in indexed columns of pandas

Let’s say I have a dataframe like following

d = {'col1': [1, 2,4,5,6], 'col2': [3, 4,5,6,7], 'col3': ['foo', 'bar', 'baz','biz', 'boo'] }    

df = pd.DataFrame(data=d) 
df.head()

   col1  col2 col3
0     1     3  foo
1     2     4  bar
2     4     5  baz
3     5     6  biz
4     6     7  boo

Now, I want to index all the columns.. indexed_df = df.set_index(['col1', 'col2', 'col3'])

How do I search for a particular value in this indexed df

Like if i want to search for baz in df I will do

df[df.col3 == 'baz']

How do I do the same thing with indexed_df

Advertisement

Answer

There are several ways:

Option 1: query

indexed_df.query('col3=="baz"')

Option 2: xs

indexed_df.xs('baz', level='col3', drop_level=False)

Option 3: get_level_values:

indexed_df.loc[indexed_df.index.get_level_values('col3')=='baz']

Let’s assume that there is some data

indexed_df = df.set_index(['col1', 'col2', 'col3']).assign(value=1)

Any of the above would give:

                value
col1 col2 col3       
4    5    baz       1
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement