I have two Pandas DataFrames, df1 and df2.
The first one specifies the 'locations' of the elements using zeros and ones.
The second one specifies the values of the elements, but not their location (i.e. it is simply filled from left to right from Col1 through Col4).
df1 = pd.DataFrame([[1,0,0,0], [1,0,0,1], [0,1,0,1], [0,1,1,1]], columns=['Col1', 'Col2', 'Col3', 'Col4'])
df2 = pd.DataFrame([[1,0,0,0], [0.4,0.6,0,0], [0.8,0.2,0,0], [0.1,0.4,0.5,0]], columns=['Col1', 'Col2', 'Col3', 'Col4'])
df1
Col1 Col2 Col3 Col4
0 1 0 0 0
1 1 0 0 1
2 0 1 0 1
3 0 1 1 1
df2
Col1 Col2 Col3 Col4
0 1 0 0 0
1 0.4 0.6 0 0
2 0.8 0.2 0 0
3 0.1 0.4 0.5 0
I would like to create a third DataFrame, df3, which places the non-zero values from df2 in the corresponding locations of ones in df1. I would like to work from left to right, i.e. the leftmost non-zero element in each row of df2 should be placed in the location of the leftmost one in df1.
df3 = pd.DataFrame([[1,0,0,0], [0.4,0,0,0.6], [0,0.8,0,0.2], [0,0.1,0.4,0.5]], columns=['Col1', 'Col2', 'Col3', 'Col4'])
df3
Col1 Col2 Col3 Col4
0 1 0 0 0
1 0.4 0 0 0.6
2 0 0.8 0 0.2
3 0 0.1 0.4 0.5
As the real DataFrames are relatively large, an efficient solution is required (i.e. looping through elements might not be an option).
Many thanks in advance for your help!