0

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

"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?

honeymoon
  • 2,400
  • 5
  • 34
  • 43

1 Answers1

4

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
mozway
  • 194,879
  • 13
  • 39
  • 75