0

I have a dataframe with three columns:

id,col1,col2

now for records where col1 is empty, I need to copy value of col2 into col1. how to do this? below is what I tried but it is not working.

df[df[col1]==''] = df['col2']
shaik moeed
  • 5,300
  • 1
  • 18
  • 54
PythonDeveloper
  • 289
  • 1
  • 4
  • 24
  • Does this answer your question? [How to pass another entire column as argument to pandas fillna()](https://stackoverflow.com/questions/30357276/how-to-pass-another-entire-column-as-argument-to-pandas-fillna) – Jason Baker Aug 24 '23 at 04:34

3 Answers3

2

You can try using if else condition. If col1 is empty then fill col2.

df['col1'] = df.apply(lambda row: row['col2'] if row['col1'] == '' else row['col1'], axis=1)
sjri
  • 93
  • 5
0

you are close,

mask = (df['col1']=='') 
# mask = df[col1].isnull() # if you are looking for Nan/null values instead of empty strings
df.loc[mask, 'col1'] = df.loc[mask, 'col2']
shaik moeed
  • 5,300
  • 1
  • 18
  • 54
  • This is actually not a good approach. You should always use `loc` to assign to a slice in a DataFrame. By chaining the slicers (`df['col1'][mask]`) you risk having a copy as intermediate which won't be updated. See [`SettingWithCopyWarning`](https://stackoverflow.com/q/20625582/16343464) – mozway Aug 24 '23 at 05:42
  • @mozway Thanks for the suggestion, updated my answer to use `loc`. – shaik moeed Aug 24 '23 at 06:07
0

You need to use loc to slice your column of interest:

df.loc[df['col1']=='', 'col1'] = df['col2']

If your indices are unique, pandas will align the right-hand side automatically.

If the indices are not unique, you can use boolean indexing:

m = df['col1']==''
df.loc[m, 'col1'] = df.loc[m, 'col2']

Or mask:

df['col1'] = df['col1'].mask(df['col1']=='', df['col2'])
mozway
  • 194,879
  • 13
  • 39
  • 75