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

Merge corresponding values from column 2 into column 1 (pandas)

I have two columns in my pandas dataframe like this:

ID          Value1      Value2
ID1         1.00        0.12
ID2         2.00        0.98
ID3         3.00        0.41
ID4         4.00        0.69

I would like to merge them, so that the corresponding value from column 2 is merged into column 1:

ID          Value1      
ID1         1.00        
Value2      0.12
ID2         2.00        
Value2      0.98
ID3         3.00        
Value2      0.41
ID4         4.00        
Value2      0.69

It is seemingly an easy logic, but I simply cannot figure this out. Any idea/help out there?
Deeply appreciated.

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 :

You can melt and post-process the columns:

out = (df
   .melt('ID', ignore_index=False)
   .assign(ID=lambda d: d['ID'].mask(d['variable'].eq('Value2'), 'Value2'))
   .sort_index().drop(columns='variable')
   .rename(columns={'value': 'Value1'})
)

Output:

       ID  Value1
0     ID1    1.00
0  Value2    0.12
1     ID2    2.00
1  Value2    0.98
2     ID3    3.00
2  Value2    0.41
3     ID4    4.00
3  Value2    0.69
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