【问题标题】:Pandas Multiindex selecting list of columns from given levelPandas Multiindex 从给定级别选择列列表
【发布时间】:2016-08-26 01:38:36
【问题描述】:

如果我制作这样的多索引列数据框:

iterables = [['bar', 'baz', 'foo', 'qux'], ['one', 'two']]
index = pd.MultiIndex.from_product(iterables, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(3, 8), index=['A', 'B', 'C'], columns=index)


first        bar                 baz                 foo                 qux  \
second       one       two       one       two       one       two       one   
A      -0.119687 -0.518318  0.113920 -1.028505  1.106375 -1.020139 -0.039300   
B       0.123480 -2.091120  0.464597 -0.147211 -0.489895 -1.090659 -0.592679   
C      -1.174376  0.282011 -0.197658 -0.030751  0.117374  1.591109  0.796908   

first             
second       two  
A      -0.938209  
B      -0.851483  
C       0.442621  

我想使用列表仅从第一组列中选择列,

select_cols=['bar', 'qux']

这样的结果是:

first        bar                  qux  
second       one       two        one        two
A      -0.119687 -0.518318  -0.039300  -0.938209    
B       0.123480 -2.091120  -0.592679  -0.851483    
C      -1.174376  0.282011   0.796908   0.442621  

我该怎么做呢? (提前谢谢)

【问题讨论】:

    标签: python pandas dataframe multi-index


    【解决方案1】:

    当我找到这个 Q/A 时,我想我可能会看到一个打印列名的解决方案。想通了,我想我可以补充一下答案。下面打印出给定级别的列名的值。

    df.columns.get_level_values(0)
    
    => ['bar', 'qux']
    

    -E

    【讨论】:

      【解决方案2】:

      简单的列选择也可以:

      df[['bar', 'qux']]
      
      # first        bar                 qux          
      # second       one       two       one       two
      # A       0.651522  0.480115 -2.924574  0.616674
      # B      -0.395988  0.001643  0.358048  0.022727
      # C      -0.317829  1.400970 -0.773148  1.549135
      

      【讨论】:

        【解决方案3】:

        您可以使用loc 选择列:

        df.loc[:, ["bar", "qux"]]
        
        #  first       bar                    qux
        # second       one        two         one         two
        #      A  1.245525  -1.469999   -0.399174    0.017094
        #      B -0.242284   0.835131   -0.400847   -0.344612
        #      C -1.067006  -1.880113   -0.516234   -0.410847
        

        【讨论】:

        • @iparjono 关于为什么它不起作用的更多原因或演示?
        • 我收到了错误KeyError: "[['bar', 'qux']] are not in ALL in the [columns]
        • 在 v0.18.1 上为我工作。
        • @iparjono 可能是版本问题。我也在0.18.1 上,它有效。
        猜你喜欢
        • 2020-08-19
        • 2013-08-30
        • 2020-05-26
        • 2021-01-25
        • 2022-06-15
        • 2019-01-26
        • 1970-01-01
        • 2017-12-21
        相关资源
        最近更新 更多