使用索引值列表切片pandas multiindex数据帧

时间:2017-09-30 17:44:39

标签: python pandas slice multi-index

我有一个看起来像

的多索引数据框

uid tid text

abc x t1

bcd y t2

uid tid 是索引。我有一个 uid 的列表,并希望获得与该列表中的 uids 对应的行,但保留第二级索引值(tid)。我想这样做而不运行任何显式循环。这可能吗?

1 个答案:

答案 0 :(得分:1)

数据:

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 +屏蔽get_level_values + isin

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

3. querydocs

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