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']
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']
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)
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']
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'])