使用索引值列表切片 pandas 多索引数据帧
Slice pandas multiindex dataframe using list of index values
我有一个多索引数据框,看起来像
uid tid 文本
abc x t1
bcd y t2
uid 和 tid 是索引。我有一个 uids 的列表,并希望在该列表中获取与 uids 对应的行,但保留第 2 级索引值(临时工)。我想在没有 运行 任何显式循环的情况下进行。这可能吗?
数据:
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)]
df1 = df.query('@L in uid')
print (df1)
text
uid tid
abc x t1
bcd y t2
我有一个多索引数据框,看起来像
uid tid 文本
abc x t1
bcd y t2
uid 和 tid 是索引。我有一个 uids 的列表,并希望在该列表中获取与 uids 对应的行,但保留第 2 级索引值(临时工)。我想在没有 运行 任何显式循环的情况下进行。这可能吗?
数据:
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)]
df1 = df.query('@L in uid')
print (df1)
text
uid tid
abc x t1
bcd y t2