我有一个多索引数据帧,其中ID_1
和ID_2
是我的索引:
ID_1 ID_2 feature_1 feature_2
1 1 0 0
2 1 1
2 1 1 1
2 0 1
我要获取的是ID_1 = 1
和feature_2 = 1
的数据
就是
ID_2 feature_1 feature_2
2 1 1
最好的方法是什么?
答案 0 :(得分:1)
将tuples
与双[]
一起用于一行DataFrame:
df1 = df.loc[[(1,2)]]
或者:
df1 = df.loc[[pd.IndexSlice[1,2]]]
print (df1)
feature_1 feature_2
ID_1 ID_2
1 2 1 1
如果仅使用一个[]
则获得Series
:
s = df.loc[(1,2)]
print (s)
feature_1 1
feature_2 1
Name: (1, 2), dtype: int64