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

Remove second duplicate row, keep fisrt and fill NaN with value from second

I have some duplicate rows in my dataframe, the first occurrence has Nan value in specific column and the second occurrence has that value in the sma ecolumn. I want to remove duplicate, keep the fisrt occurrence and replace Nan value with value from second occurrence. Like this:

Name Rank City
Andre Ryan NaN London
Andre Ryan 86 Paris
…-

The goal

Name Rank City
Andre Ryan 86 London

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

>Solution :

Here’s one way to dedup by using groupby and agg on this example dataset:

enter image description here

import pandas as pd

#create the test table
df = pd.DataFrame({
    'Name':['A','A','B','C','B','C'],
    'Rank':[None,1,None,None,2,3],
    'City':['q','r','s','t','u','v'],
})

#groupby and agg to dedup
dedup_df = df.groupby('Name').agg(
    Rank = ('Rank',lambda ranks: ranks.dropna().iloc[0]),
    City = ('City','first'),
).reset_index()

dedup_df

Output

enter image description here

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