Setting index as multindex format without being multindex

Viewed 30

I have this data:

df = pd.DataFrame({'X1':[0,5,4,8,9,0,7,6],
                   'X2':[4,1,3,5,6,2,3,3],
                   'X3':['A','A','B','B','B','C','C','C']})    
df = df.set_index('X3')

I want to set X3 as index so I would do:

df = df.set_index('X3')

And the result is:

enter image description here

However, I'm looking to set the same index but as a multi-index format (even if it's not a multi-index). This is the expected result:

    X1 X2 
A   0  4  
    5  1  
B   4  3  
    8  5  
    9  6  
C   0  2  
    7  3  
    6  3  

Is that possible?

EDIT

Answering the comments, the reason I want to achieve this is that I want to order df by X1 values without losing "the grouping" of X3, so I would be able to see the order in each X3 group. I can't do it with sort_values(['X3', 'X1'], ascending=[False, False]) because the first condition of sorting must be the maximum of each group keeping all rows from the same group together. So I can see the group that has the maximum X1 and immediately see how are the other values of the same group, then the second group contains the second maximum of X1 and immediately see how are the other values of the second group, and so on.

2 Answers

Not sure if this helps; but what if you first get rid of repeated values from 'X3' columns then set that as index...

import pandas as pd 
df = pd.DataFrame({'X1':[0,5,4,8,9,0,7,6],
                   'X2':[4,1,3,5,6,2,3,3],
                   'X3':['A','A','B','B','B','C','C','C']})    

lst_index = [] 
for x in df["X3"]:
    if x in lst_index:
        lst_index.append("")
    else:
        lst_index.append(x)

del df["X3"] # delete this column if not required anymore...
df.index = lst_index

# Output

    X1  X2
A   0   4
    5   1
B   4   3
    8   5
    9   6
C   0   2
    7   3
    6   3

try:

df
    X1  X2  X3
0   0   4   A
1   5   1   A
2   4   3   B
3   8   5   B
4   9   6   B
5   0   2   C
6   7   3   C
7   6   3   C

df = df.set_index('X3')
new_index = pd.Series([i if not j else '' for i, j in list(zip(df.index, df.index.duplicated())) ])
df = df.set_index(new_index)

    X1  X2
A   0   4
    5   1
B   4   3
    8   5
    9   6
C   0   2
    7   3
    6   3
Related