Slice pandas multiindex dataframe using list of index values [duplicate]

安稳与你 提交于 2019-12-31 03:43:09

问题


I have a multi-index dataframe that looks like

uid tid text

abc x t1

bcd y t2

uid and tid are the indexes. I have a list of uids, and want to get the rows corresponding to the uids in that list, but keeping the 2nd level index values (tid). I want to do it without running any explicit loop. Is that possible?


回答1:


Data:

L = ['abc', 'bcd']

print (df)
         text
uid  tid     
abc  x     t1
abc1 x     t1
bcd  y     t2

1.slicers

idx = pd.IndexSlice
df1 = df.loc[idx[L,:],:]

2.boolean indexing + mask with get_level_values + isin:

df1 = df[df.index.get_level_values(0).isin(L)]

3.query, docs:

df1 = df.query('@L in uid')
print (df1)
        text
uid tid     
abc x     t1
bcd y     t2


来源:https://stackoverflow.com/questions/46505427/slice-pandas-multiindex-dataframe-using-list-of-index-values

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