EN VI

Python - Merge corresponding values from column 2 into column 1 (pandas)?

2024-03-13 00:00:06
How to Python - 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.

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
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login