【问题标题】:Deleting a column from MultiIndex Pandas dataframe从 MultiIndex Pandas 数据框中删除一列
【发布时间】:2018-03-01 14:21:15
【问题描述】:

我一直在尝试了解 Pandas 的多索引方法。我正在尝试删除“std”子列,但徒劳无功。

如何做到这一点?

                                    attribute                           attribute2  \
                                        test1            std           test2   
d         count       type                                                  
r1         10          rx      0.559 (0.0)    0.559 (0.0)    0.568 (0.0)   
                     sth1      0.653 (0.004)  0.653 (0.004)  0.679 (0.002)   
                     sth2      0.584 (0.002)  0.584 (0.002)  0.586 (0.003)   
                     sth3      0.651 (0.005)  0.651 (0.005)  0.676 (0

我想我似乎无法理解 https://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.drop.html 函数。

因此,生成的数据框应该只有两个平均列,没有“std” 非常感谢。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我认为更好的是删除所有带有std 的列是MultiIndex 的第二级使用drop 和参数level=1:

    print (df)
                  attribute          attribute2          attribute3         
                      test1      std      test2      std      test3      std
    d  count type                                                           
    r1 10    rx       0.559    (0.0)      0.559    (0.0)      0.568    (0.0)
             sth1     0.653  (0.004)      0.653  (0.004)      0.679  (0.002)
             sth2     0.584  (0.002)      0.584  (0.002)      0.586  (0.003)
             sth3     0.651  (0.005)      0.651  (0.005)      0.676      (0)
    
    df = df.drop('std', axis=1, level=1)
    print (df)
                  attribute attribute2 attribute3
                      test1      test2      test3
    d  count type                                
    r1 10    rx       0.559      0.559      0.568
             sth1     0.653      0.653      0.679
             sth2     0.584      0.584      0.586
             sth3     0.651      0.651      0.676
    

    【讨论】:

    • 谢谢,这样更优雅!
    【解决方案2】:

    一位同事提醒我,我没有正确使用列的索引。要从多索引数据框对象中删除列,我只是这样做了:

    f2 = f2.drop([('accuracy','std')],axis=1).drop([('F1','std')],axis=1)
    

    【讨论】:

      猜你喜欢
      • 2017-08-07
      • 1970-01-01
      • 2021-06-14
      • 2019-10-29
      • 1970-01-01
      • 1970-01-01
      • 2019-01-06
      • 2013-01-17
      • 2017-09-10
      相关资源
      最近更新 更多