Search code examples
pythonpandasmulti-indexdrop

Drop column from MultiIndex df


I apologize if this question is repeated, I was unable to find a working solution with previous answers.

Problem: I am looking to drop a column from a multi-index dataframe. The column in question appears as a level. In particular I wish to drop the entire column 'typeE'

Methodology I have attempted to drop it using .drop() but must be missing some specification (df.drop(['typeE'],axis=1, level=0))

This is how the df is structured. I wish to drop the column typeE (all of it)

[Input]    df.columns
[Output]   MultiIndex(levels=[['typeA', 'typeB', 'typeC', 'typeD', 'typeE', 'typeF'], ['stock', 'bond', 'cash']],
           labels=[[0, 1, 2, 3, 4, 5, 6], [1, 0, 1, 2, 0, 2]])

[Input]    df.index
[Output]   DatetimeIndex(['2005-06-30', '2005-07-01', '2005-07-02'], dtype='datetime64[ns]', length=3, freq=None)

[Input]    df
[Output]

              typeA      typeB       typeC       typeD       typeE        typeF
              bond       stock        bond       cash        stock        cash
2005-06-30  0.000132    0.358719    0.018888    0.132677    0.034894    0.099345
2005-07-01  0.000167    0.353419    0.018719    0.139574    0.018923    0.024892
2005-07-02  0.002300    0.357893    0.011425    0.130605    0.037289    0.028304        

Solution

  • You can try drop

    df = df.drop(('typeE','stock'),1)
    df
    Out[14]: 
    index          typeA     typeB     typeC     typeD     typeF
    0               bond     stock      bond      cash      cash
    2005-06-30  0.000132  0.358719  0.018888  0.132677  0.099345
    2005-07-01  0.000167  0.353419  0.018719  0.139574  0.024892
    2005-07-02  0.002300  0.357893  0.011425  0.130605  0.028304