Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pandas replace empty cell with value of another column

I want to replace the cells of column A with the value of column B, if the value of columns A is empty:

import pandas as pd
df = pd.DataFrame({'A':[1, 2, '', 4, ''], 'B':[6, 7, 8, 9, 10]})

Should return:

   A   B
   1   6
   2   7
   8   8
   4   9
   10  10

I tried to replace the empty values of columns A but I got an

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"Series.replace cannot use dict-value and " ValueError: Series.replace cannot use dict-value and non-None to_replace

df['A'] = df['A'].replace('', df['B'])

How can I replace the empty cells?

>Solution :

You can replace ” by NA, then bfill:

df.replace('', pd.NA).bfill(axis=1)

Or use fillna:

df['A'] = df['A'].replace('', pd.NA).fillna(df['B'])

output:

    A   B
0   1   6
1   2   7
2   8   8
3   4   9
4  10  10
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading