user1464878
user1464878

Reputation:

How to replace with values with adjacent column using pandas

I have dataframe, df1,

After outer join the df is below

df1 have 4 columns ['A','B','C','D']

ID,A,B,C,D
1,Nan,Nan,c,d
1,a,b,c,d

expected out is below

ID,A,B,C,D
1,c,d,c,d
1,a,b,c,d

in the first row df['A'] replaced with df['C'], if df['A'] then it has to retrieve df['A'] only

in the first row df['B'] replaced with df['D'], if df['B'] then it has to retrieve df['D'] only

Upvotes: 1

Views: 1044

Answers (1)

jcaliz
jcaliz

Reputation: 4041

You need to fill the column with the second-after column, one way is to fillna specifying the value parameter:

df.A.fillna(value=df.C, inplace=True)
df.B.fillna(value=df.D, inplace=True)

If for some reason you have a lot of columns and wants to keep filling NaN using values on the second-after column then use a for loop on the first n-2 columns

columns = ['A', 'B', 'C', 'D']

for i in range(len(columns)-2):
    df[columns[i]].fillna(df[columns[i+2]], inplace=True)

Upvotes: 1

Related Questions