How to replace columnA with columnB in pandas dataframe by skipping the empty values in columnB

Viewed 85

I have 2 columns A and B ,

Column A  Column B

1          
2         4
3

I want to replace ColumnA with ColumnB but it should only replace non-empty values .

Expected output

coulmnA
1
4
3

and it should not be

CoulmnA

4

please let me know how can I achieve this , I tries to use df.replace but it copies all the values .

2 Answers
df.loc[df['Column_B'] != '','Column_A'] = df['Column_B']

print(df)

Prints:

  Column_A Column_B
0        1         
1        4        4
2        3         

This can easily be done using the apply function and lambda function combined to make it vectorized and this very fast.

df = pd.DataFrame({'coulmnA': ['sad', 'ddsf', 'abc' ], 'coulmnB': ['', 'sdf', '']})
df

Out[1]:


  coulmnA  coulmnB
0   sad    ddsf
1   ddsf   None
2   abc    None
df.coulmnB = df.apply(lambda x: x.coulmnB if not x.coulmnB == '' else x.coulmnA, axis=1)
df

Out[2]:

   coulmnA  coulmnB
0   sad     ddsf
1   sdf     sdf
2   sdfa    sdfa

Related