从MultiIndex Pandas数据帧中删除列

问题描述 投票:3回答:2

我一直在努力理解Pandas的多指标方法。我试图删除“标准”子列,但是徒劳无功。

如何才能做到这一点?

                                    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功能。

结果数据框因此应该只有两个平均列,没有“标准”非常感谢。

python pandas
2个回答
3
投票

我认为更好的是删除所有列stdMultiIndex的第二级使用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

0
投票

一位同事提醒我,我没有正确使用列的索引。要从多索引数据框对象中删除列,我只需执行以下操作:

f2 = f2.drop([('accuracy','std')],axis=1).drop([('F1','std')],axis=1)
© www.soinside.com 2019 - 2024. All rights reserved.