Let’s say I have a dataframe like following
JavaScript
x
12
12
1
d = {'col1': [1, 2,4,5,6], 'col2': [3, 4,5,6,7], 'col3': ['foo', 'bar', 'baz','biz', 'boo'] }
2
3
df = pd.DataFrame(data=d)
4
df.head()
5
6
col1 col2 col3
7
0 1 3 foo
8
1 2 4 bar
9
2 4 5 baz
10
3 5 6 biz
11
4 6 7 boo
12
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
JavaScript
1
2
1
df[df.col3 == 'baz']
2
How do I do the same thing with indexed_df
Advertisement
Answer
There are several ways:
Option 1: query
JavaScript
1
2
1
indexed_df.query('col3=="baz"')
2
Option 2: xs
JavaScript
1
2
1
indexed_df.xs('baz', level='col3', drop_level=False)
2
Option 3: get_level_values
:
JavaScript
1
2
1
indexed_df.loc[indexed_df.index.get_level_values('col3')=='baz']
2
Let’s assume that there is some data
JavaScript
1
2
1
indexed_df = df.set_index(['col1', 'col2', 'col3']).assign(value=1)
2
Any of the above would give:
JavaScript
1
4
1
value
2
col1 col2 col3
3
4 5 baz 1
4