简体   繁体   中英

Filtering on index levels in a pandas.DataFrame

If I have a multiindex dataframe:

import pandas as pd
df = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]],columns=['a','b','c']).set_index(['a','b'])

I can simply filter the dataframe on a column, for example:

df[df.c>4]

But to do the same on the level of an index, say "b", I can't do:

df[df.b>4]

Instead I can do:

df[df.index.get_level_values('b')>4]

But is there a less verbose way to do this?

You can use query for better readability

In [795]: df.query('b > 4')
Out[795]:
     c
a b
4 5  6
7 8  9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM