Gingerhaze
Gingerhaze

Reputation: 676

Rearrange Multiindex Columns By Name

I have a df with multi-index columns similar to this format:

103   103 B  103 C      111           121       93
CPS   CPS    CPS    Conc  MConc   Conc  MConc  CPS
 1     1      1       1    100     4     400    1
 2     3      4       2    200     5     500    2
 3     3      3       3    300     6     600    3

What I'd like to do is move all the columns that contain CPS to the end of the dataframe. Like so,

    111           121      93   103   103 B  103 C
Conc  MConc   Conc  MConc  CPS  CPS   CPS    CPS
 1    100     4     400    1     1     1      1
 2    200     5     500    2     2     3      4
 3    300     6     600    3     3     3      3

I've tried sorting the index, or swapping the levels and sorting but this moves columns I don't want to move and doesn't sort them in the correct order. There are over 37 columns so I don't want to manually pass column names.

How can I select the columns where level 1 contains CPS and move those columns to the end of the dataframe?

Upvotes: 0

Views: 42

Answers (1)

BENY
BENY

Reputation: 323276

Try with argsort with get_level_values

out = df.iloc[:,np.argsort(df.columns.get_level_values(1)=='CPS')]
Out[425]: 
   111        121       103 103B 103C  93
0 Conc MConc Conc MConc CPS  CPS  CPS CPS
1    1   100    4   400   1    1    1   1
2    2   200    5   500   2    3    4   2
3    3   300    6   600   3    3    3   3

Upvotes: 1

Related Questions