【发布时间】:2018-03-12 08:08:06
【问题描述】:
我有一个看起来像的多索引数据框
uid tid 文本
abc x t1
bcd y t2
uid 和 tid 是索引。我有一个 uid 列表,并且想要获取与该列表中的 uids 对应的行,但保留第二级索引值 (tid)。我想在不运行任何显式循环的情况下做到这一点。这可能吗?
【问题讨论】:
标签: python pandas slice multi-index
我有一个看起来像的多索引数据框
uid tid 文本
abc x t1
bcd y t2
uid 和 tid 是索引。我有一个 uid 列表,并且想要获取与该列表中的 uids 对应的行,但保留第二级索引值 (tid)。我想在不运行任何显式循环的情况下做到这一点。这可能吗?
【问题讨论】:
标签: python pandas slice multi-index
数据:
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)]
df1 = df.query('@L in uid')
print (df1)
text
uid tid
abc x t1
bcd y t2
【讨论】:
df = df.sort_index()排序,然后用第一种方法。 sorting 解释'In 97'