Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Join and overwrite an attribute in the same dataframe

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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.

>Solution :

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               
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading