熊猫:带条件的多索引

时间:2018-12-17 08:48:29

标签: python pandas dataframe multi-index

我有一个多索引数据帧,其中ID_1ID_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 = 1feature_2 = 1的数据 就是

ID_2 feature_1 feature_2 
  2      1        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