删除多级索引熊猫级别的元素

时间:2016-07-27 14:18:55

标签: python pandas indexing multi-index

在以下DataFrame中有一个2级MultiIndex,即citydate

                 temp
                count
city date            
SFO  2014-05-31    31
     2014-06-30    30
     2014-07-31    31
     2014-08-31    31
     2014-09-30    30
YYZ  2014-05-31    31
     2014-06-30    30
     2014-07-31    31
     2014-08-31    31
     2014-09-30    30

我想从日期级别删除2014-05-312014-09-30

我该怎么做?

评论:构建DataFrame -

df = pd.DataFrame(
    {('temp', 'count'): {('SFO', Timestamp('2014-05-31 00:00:00')): 31,
                         ('SFO', Timestamp('2014-06-30 00:00:00')): 30,
                         ('SFO', Timestamp('2014-07-31 00:00:00')): 31,
                         ('SFO', Timestamp('2014-08-31 00:00:00')): 31,
                         ('SFO', Timestamp('2014-09-30 00:00:00')): 30,
                         ('YYZ', Timestamp('2014-05-31 00:00:00')): 31,
                         ('YYZ', Timestamp('2014-06-30 00:00:00')): 30,
                         ('YYZ', Timestamp('2014-07-31 00:00:00')): 31,
                         ('YYZ', Timestamp('2014-08-31 00:00:00')): 31,
                         ('YYZ', Timestamp('2014-09-30 00:00:00')): 30}}
).rename_axis(['city','date'])

1 个答案:

答案 0 :(得分:7)

您可以drop具体level

In[4]: df.drop([Timestamp('2014-05-31'),Timestamp('2014-09-30')],level=1)
Out[4]: 
                 temp
                count
city date            
SFO  2014-06-30    30
     2014-07-31    31
     2014-08-31    31
YYZ  2014-06-30    30
     2014-07-31    31
     2014-08-31    31