'How to merge every two columns, with pandas, substituting only if the left column value is nan or 0 [duplicate]

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.



Solution 1:[1]

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'])

Solution 2:[2]

First, a dataframe is created from the dictionary. Then all 0 are replaced by np.nan. This has the advantage that you can use the fillna() function afterwards to replace all np.nan values with the corresponding value from col2.

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()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2