如何从多索引数据框中返回多个级别/组的值?

Nov*_*vus 4 python multi-index dataframe pandas

这是我的多索引数据框:

# Index Levels
outside = ['G1','G1','G1','G2','G2','G2']
inside = [1,2,3,1,2,3]
hier_index = list(zip(outside,inside))
hier_index = pd.MultiIndex.from_tuples(hier_index)
df = pd.DataFrame(np.random.randn(6,2),index=hier_index,columns=['A','B'])
df.index.names = ['Group','Num']
df
Run Code Online (Sandbox Code Playgroud)

数据框如下所示:

                  A           B
Group   Num     
G1      1     0.147027  -0.479448
        2     0.558769   1.024810
        3    -0.925874   1.862864
G2      1    -1.133817   0.610478
        2     0.386030   2.084019
        3    -0.376519   0.230336
Run Code Online (Sandbox Code Playgroud)

我想要实现的是返回Group G1and G2, Num 1and 中的值,3如下所示:

G1     1     0.147027   -0.479448
       3    -0.925874    1.862864
G2     1    -1.133817    0.610478
       3    -0.376519    0.230336
Run Code Online (Sandbox Code Playgroud)

我试过了

df.loc[['G1','G2']].loc[[1,3]]
Run Code Online (Sandbox Code Playgroud)

但它什么也没显示。

然后我试过了

df.xs([['G1','G2'],[1,3]]) 
Run Code Online (Sandbox Code Playgroud)

但它返回

TypeError: '(['G1', 'G2'], [1, 3])' 是一个无效的键。

有什么办法可以让它返回Group G1and 中的值G2Num 1and3吗?

jez*_*ael 5

DataFrame.loc与列表一起使用:

df1 = df.loc[(['G1','G2'], [1,3]), :]
print (df1)
                  A         B
Group Num                    
G1    1    2.165594  0.466762
      3    0.451996  0.125071
G2    1    2.783947  0.176145
      3    0.169508  0.071441
Run Code Online (Sandbox Code Playgroud)

或使用切片器

idx = pd.IndexSlice
df1 = df.loc[idx[['G1','G2'], [1,3]], :]
print (df1)
                  A         B
Group Num                    
G1    1    0.617367 -1.010116
      3   -0.990257 -1.262942
G2    1    1.336134 -0.198787
      3   -0.310426  1.063520
Run Code Online (Sandbox Code Playgroud)


Cle*_*leb 5

作为 的替代 .loc,您还可以query像这样使用:

df.query('Group in ["G1", "G2"] and Num in [1, 3]')
Run Code Online (Sandbox Code Playgroud)

它还返回:

                  A         B
Group Num                    
G1    1   -1.749477 -0.276759
      3    0.888542 -0.656236
G2    1    0.757631 -1.091000
      3   -1.203232  1.702107
Run Code Online (Sandbox Code Playgroud)

如果您愿意,您还可以在查询中使用参数,@如果您有很长的列表,可能会派上用场:

num_sel = [1, 3]
df.query('Group in ["G1", "G2"] and Num in @num_sel')
Run Code Online (Sandbox Code Playgroud)

产生相同的输出。

然后,您还可以轻松地对列条目添加其他约束,例如,中的值A必须大于0

df.query('Group in ["G1", "G2"] and Num in [1, 3] and A > 0')
Run Code Online (Sandbox Code Playgroud)

返回

                  A         B
Group Num                    
G1    3    0.888542 -0.656236
G2    1    0.757631 -1.091000
Run Code Online (Sandbox Code Playgroud)

  • 不知道我们可以使用这样的查询。谢谢您的启发。 (2认同)