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