Home > Net >  Join and overwrite an attribute in the same dataframe
Join and overwrite an attribute in the same dataframe

Time:11-25

If I have this dataframe:

# data
data = [['london_1', 10,'london'], ['london_2', 15,'london'], ['london_3', 14,'london'],['london',49,'']]
  
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['station', 'info','parent_station'])

So:

    station  info parent_station
0  london_1    10         london
1  london_2    15         london
2  london_3    14         london
3    london    49               

I would like to overwrite the info value of the child station according to the info value of the parent station:

    station  info parent_station
0  london_1    49         london
1  london_2    49         london
2  london_3    49         london
3    london    49               

Is there a simple way to do that ?

Additional information:

  • There could be more than one parent station, but only one parent station per station.

CodePudding user response:

You can map then condition assign

df.loc[df.parent_station.ne(''),'info'] = df.parent_station.map(df.set_index('station')['info'])
df
Out[329]: 
    station  info parent_station
0  london_1  49.0         london
1  london_2  49.0         london
2  london_3  49.0         london
3    london  49.0               
  • Related