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

Impute Pandas dataframe column with value from another row based on ID column

df:

id   name 
0    toto                    
1    tata
0    NaN

I would like to impute the name column missing value on the third row based on the id.
The desired dataframe would be:

id   name 
0    toto                    
1    tata
0    toto

I did the following:

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

df.loc[df.name.isna(), "name"] = df["id"].map(df["name"])

but it is not working.

>Solution :

import pandas as pd
df = pd.DataFrame({'id':[0,1,0],
              'name':['toto','tata',pd.NA]})

df = df[['id']].merge(df[pd.notna(df['name'])],
                      how = 'left', 
                      on = 'id')
df
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