Pandas Multiindex dataframe remove rows

萝らか妹 提交于 2019-12-06 07:28:44

One way is to use the index method get_level_values():

df
       col
i1 i2     
a  c     5
   d     6
b  c     7
   d     8

df[df.index.get_level_values(0).isin(idx_to_keep)]
       col
i1 i2     
a  c     5
   d     6

You are looking for .xs:

df.xs('a', axis=0, level=0, drop_level=False)

Which gives:

       col
i1 i2     
a  c     5
   d     6

You can just use loc:

df.loc[['a']]

The resulting output:

       col
i1 i2     
a  c     5
   d     6

Let's use slice

idx_to_keep = ['a']
df.loc[slice(*idx_to_keep,)]

Output:

       col
i1 i2     
a  c     5
   d     6
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!