How can I reorder multi-indexed dataframe columns at a specific level

后端 未结 4 1288
时光取名叫无心
时光取名叫无心 2020-12-17 08:25

I have a multi-indexed DataFrame with names attached to the column levels. I\'d like to be able to easily shuffle the columns around so that they match the ord

4条回答
  •  醉话见心
    2020-12-17 09:29

    This is the simplest one that worked for me:

    1 - for your selected level, create a list with columns in desired order;

    2 - reindex your columns and create a MultiIndex object from that list, keep in mind this returns a tuple;

    3 - use the MultiIndex object to reorder your DataFrame.

    cols = ['IWWGCW', 'IWWGDW', 'BASE']
    
    new_cols = df.columns.reindex(cols, level = 0)
    
    df.reindex(columns= new_cols[0]) #new_cols is a single item tuple
    

    in one line:

    df.reindex(columns= df.columns.reindex(['IWWGCW', 'IWWGDW', 'BASE'], 
    level = 0)[0])
    

    voilá

提交回复
热议问题