Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to stack two columns

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading