I have 2n columns and each pair looks like this:
1 0
2 0
45 1
44 10
43 22
0 55
0 46
0 75
I want to turn each pair of columns into a single one where the 0 or NaN of the left column are substituted by the values on the right column. In this example the result would be
1
2
45
44
43
55
46
75
And it is important that this is done for every pair of columns in the dataframe.
CodePudding user response:
try this :
import pandas as pd
import numpy as np
d = {'col1': [1,2,45,44,43,0,0,0,2],
'col2': [0,0,1,10,22,55,46,75,np.nan],
}
df = pd.DataFrame(data=d)
df=df.replace(np.nan,0)
df['col2']=np.where(df['col1']==0,df['col2'],df['col1'])
CodePudding user response:
import pandas as pd
import numpy as np
d = {'col1': [0,0,1,10,22,55,46,34,np.nan],
'col2': [1,2,45,44,43,0,0,0,2]}
df = pd.DataFrame(d)
df.replace(0, np.nan, inplace=True)
df['col1'].fillna(df['col2']).to_frame()