-1

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.

rdlc7
  • 1
  • 1

2 Answers2

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'])
DataSciRookie
  • 798
  • 1
  • 3
  • 12
0

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()
yllwpr
  • 175
  • 2
  • 10
  • 1
    Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you [edit] your answer to include an explanation of what you're doing** and why you believe it is the best approach? – Jeremy Caney May 08 '22 at 00:13