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 merge 3 columns into 1 whilst keeping values column separate

I have the following Pivot table:

Subclass Subclass2 Layer Amount
A B C 5
E F G 100

I want to merge the 3 columns together and have Amount stay separate to form this:

Col1 Amount
A NaN
B NaN
C 5
E NaN
F NaN
G 100

So Far I’ve turned it into a regular DataFrame and did this:

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

df.melt(id_vars = ['SubClass', 'SubClass2'], value_name = 'CQ')

But that didn’t arrange it right at all. It messed up all the columns.

I’ve thought once I get the melt right, I could just change the NaN values to 0 or blanks.

EDIT

I need to keep Subclass & Subclass2 in the final column as they’re the higher level mapping of Layer, hence why I want the output Col1 to include them before listing Layer with Amount next to it.

Thanks!

>Solution :

here is one way to do it

pd.concat([df,
           df[['Subclass','Subclass2']].stack().reset_index()[0].to_frame().rename(columns={0:'Layer'})
          ]
         )[['Layer','Amount']].sort_values('Layer')
    Layer   Amount
0      A    NaN
1      B    NaN
0      C    5.0
2      E    NaN
3      F    NaN
1      G    100.0

enter image description here

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