Home > Blockchain >  changing row values into multi index
changing row values into multi index

Time:10-07

Considering this sample data:

          mem   Admits  AdmPerK
Month           
JAN        1       2    3
FEB        4       5    6

I am attempting, I think, to introduce a multi index and create this result:

          JAN                       FEB
<index>   mem   Admits  AdmPerK     mem Admits  AdmPerK    
                
    0     1      2       3          4     5      6

Tried the following;

df.columns = pd.MultiIndex.from_tuples(df.columns) 
df.T

Neither worked nor did a couple of other transformation attempts. Thanks for taking the time to look at this.

CodePudding user response:

You can do the job by chaining stack, to_frame and T (for transpose). To give a specific name to the final index, use the parameter name in to_frame. With an example

#input data
df = pd.DataFrame({'Month': ['JAN', 'FEB'], 'mem': [1, 4], 
                   'Admits': [2, 5], 'AdmPerK': [3, 6]})
df = df.set_index('Month')
print(df)
#        mem  Admits  AdmPerK
# Month                      
# JAN      1       2        3
# FEB      4       5        6

#reshape
res = df.stack().to_frame(name='whatyouwant').T
print(res)
Month       JAN                FEB               
            mem Admits AdmPerK mem Admits AdmPerK
whatyouwant   1      2       3   4      5       6
  • Related