Slice Pandas Multiindex Dataframe Using List Of Index Values
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
Solution 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)]
df1 = df.query('@L in uid')
print (df1)
text
uid tid
abc x t1
bcd y t2
Post a Comment for "Slice Pandas Multiindex Dataframe Using List Of Index Values"