使用索引值列表对Pandas MultiIndex DataFrame进行切片 [英] Slice pandas multiindex dataframe using list of index values

查看:207
本文介绍了使用索引值列表对Pandas MultiIndex DataFrame进行切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多索引数据框,看起来像

I have a multi-index dataframe that looks like

uid tid文字

abc x t1

bcd y t2

uid tid 是索引.我有一个 uid 的列表,并且想要获取与该列表中 uids 相对应的行,但要保留第二级索引值(tid).我想在不运行任何显式循环的情况下执行此操作.有可能吗?

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?

推荐答案

数据:

L = ['abc', 'bcd']

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

1.切片器

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


2. boolean indexing +遮罩与 get_level_values + isin :


2.boolean indexing + mask with get_level_values + isin:

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


3. query 文档:

df1 = df.query('@L in uid')

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

这篇关于使用索引值列表对Pandas MultiIndex DataFrame进行切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆