python - Pandas 在 MultiIndex DataFrame 中选择特定的低级列

标签 python pandas multi-index

不知道这个问题有没有被再次回答,但是我没有找到类似的东西

我有一个包含两级列的 MultiIndex DataFrame,例如:

arrays = [np.array(['bar', 'bar','bar', 'foo', 'foo','foo', 'qux', 'qux', 'qux']),
          np.array(['one', 'two', 'three', 'one', 'two', 'three', 'one', 'two','three'])]

df = pd.DataFrame(np.random.randn(3, 9), columns=arrays)
print(df)

        bar                           foo                           qux  \
        one       two     three       one       two     three       one   
0  1.255724 -0.692387 -1.485324  2.265736  0.494645  1.973369 -0.326260   
1 -0.903874  0.695460 -0.950076  0.181590 -2.345611  1.288061  0.980166   
2 -0.294882  1.034745  1.423288 -0.895625 -0.847338  0.470444  0.373579   


        two     three  
0  0.136427 -0.136479  
1  0.702732 -1.894376  
2  0.506240 -0.456519  

我想为每个第一级列独立地从第二级选择特定列。

例如,我想得到这样的结果:

        bar                 foo       qux          
        one       two       two       one     three
0  1.255724 -0.692387  0.494645 -0.326260 -0.136479
1 -0.903874  0.695460 -2.345611  0.980166 -1.894376
2 -0.294882  1.034745 -0.847338  0.373579 -0.456519

我已经看到了这个 questions,但这不是我想要实现的。

现在我是这样做的:

level0 = ['bar','foo','qux']
level1 = [['one','two'],['two'],['one','three']]

df_list=[]
for i,value in enumerate(level0):
    df_list.append(df.loc[:,(value,level1[i])])
new_df = pd.concat([i for i in df_list],axis=1)
print(new_df)

但在我看来这并不是最好的解决方案。

有没有更好的(更多“pandas”)方法来解决这个问题?

最佳答案

您可以先挑出列,然后使用列提取,而不是连接数据;

cols = pd.concat([pd.DataFrame({'level_0':x, 'level_1':y}) 
                  for x,y in zip(level0,level1)]
                ).values

df[cols]

输出:

        bar                 foo       qux          
        one       two       two       one     three
0  0.729061 -0.876547  0.312557  0.736568  0.250469
1  0.619194  0.451023  0.803252 -1.636403 -0.854607
2  0.254690 -1.054859 -1.223274  0.398411 -1.448396

关于python - Pandas 在 MultiIndex DataFrame 中选择特定的低级列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60155989/

相关文章:

python - 获取 pandas 中包含特定值的列名

python - Pandas:使用 [column name][row_number] 选择数组的值仅适用于 multiindex

python - 如何使用 BeautifulSoup 更改标签名称?

python - pandas 数据框标签列编码

python - 创建两个列表的组合,直到一个列表中的值高于另一个列表中的值?

python - 删除 Pandas 中索引未唯一标识的行

python - Pandas 多索引 DataFrame 为每个索引添加子索引

python - 导入错误 : No module named 'xmltodict'

python - 将一列按另一列的值分组

pandas - 使用 multiindex 更改 pandas DataFrame 中的索引顺序