Home > OS >  how to stack two columns
how to stack two columns

Time:11-09

I have a df as this:

                                 C  CF
NO FROMNODENO TONODENO                
1  1          2         582.551074   0
   2          1         809.018213   0

and I would like to obtain this:

                                   new value
NO FROMNODENO TONODENO new index            
1  1          2        C          582.551074
   2          1        C          809.018213
   1          2        CF           0.000000
   2          1        CF           0.000000

Note that there could be more columns at the beginning and some of them should not change. How to do it? And how to set the name of the new index the values of which come from the labels of the stack indices?

CodePudding user response:

Use DataFrame.rename_axis for rename last level with DataFrame.stack, for one column DataFrame use Series.to_frame:

df = df.rename_axis('new index', axis=1).stack().to_frame('new value')
print (df)
                                   new value
NO FROMNODENO TONODENO new index            
1  1          2        C          582.551074
                       CF           0.000000
   2          1        C          809.018213
                       CF           0.000000

CodePudding user response:

Can stack and unstack. Rename columns as may be appropriate

df.stack().unstack(level=0).rename(columns={1:'new value'}).reset_index()
  • Related