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

When your pandas df has a column of list type removing duplicates from each item

My dataframe has a column of lists and looks like this.

     id  source
0    3   [nan,nan,nan]
1    5   [nan,foo,foo,nan,foo]
2    7   [ham,nan,ham,nan]
3    9   [foo,foo]

I need to remove duplicates from each list. So I am looking from something like below.

     id  source
0    3   [nan]
1    5   [nan,foo]
2    7   [ham,nan]
3    9   [foo]

I tried to use the following code which didn’t work. What do you recommend?

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['source'] = list(set(df['source']))

>Solution :

You can .explode on source column, .drop_duplicates and .groupby back:

df = (
    df.explode("source")
    .drop_duplicates(["id", "source"])
    .groupby("id", as_index=False)
    .agg(list)
)
print(df)

Prints:

   id      source
0   3       [nan]
1   5  [nan, foo]
2   7  [ham, nan]
3   9       [foo]

Or convert the list to pd.Series, drop duplicates and convert back to list:

df["source"] = df["source"].apply(lambda x: [*pd.Series(x).drop_duplicates()])
print(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