LdM
LdM

Reputation: 704

Updating a Pandas dataframe by replacing NaN values in a column with not NaN values from another column

I'd need to update an original dataframe in case there is a match between an object having NaN value but that has a match when it is within Field with another object.

Giving you an example:

Original df:

Object Field (other columns)
house  Christmas 
table  house
tablet nan
Christmas  nan
chair  table
oven   nan
house  bottle
bottle nan
  

I'd have at the end a table which looks as follows

df1

Object Field (other columns)
house  Christmas 
table  house
Christmas  house
chair  table
oven   nan
house  bottle
bottle house

For updating the original dataframe, I guess that I'd check each object where there is a NaN value in the Field column and, for each of them, check if it has an Object correspondence when it is in the Field column. Any help would be great.

Upvotes: 0

Views: 561

Answers (1)

SeaBean
SeaBean

Reputation: 23217

You can create a mapping from Field and Object columns of df. Then, use that mapping on NaN entries of Field to get the corresponding Object values in other rows to fill-up the NaN values, as follow:

mapping = df.loc[df['Field'].notna()].set_index('Field')['Object']
mapping = mapping.groupby(level=0).first()    # Use the first entry if more than one

df1 = df.copy()
df1.loc[df1['Field'].isna(), 'Field'] = df1['Object'].map(mapping)

Result:

print(df1)

      Object      Field
0      house  Christmas
1      table      house
2     tablet        NaN
3  Christmas      house
4      chair      table
5       oven        NaN
6      house     bottle
7     bottle      house

Upvotes: 1

Related Questions