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

Is there a simple way to remove duplicate values in certain cells of a dataframe column?

I have a dataframe column with city locations and some of the cells have the same value (city) twice within each cell. I was wondering how to get rid of one of the values. eg. Instead of it saying Dublin Dublin below it will only say Dublin once.

I have tried df['city'].apply(set) but it doesn’t give me what I am looking for.

Any advice much appreciated. Please see the image below:

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

enter image description here

>Solution :

You can split each item by (space) and convert each list of split strings to a set (which is deduplicated, but not sorted), and then re-join:

df['city'] = df['city'].str.split().apply(set).str.join(' ')

Output:

>>> df
             city
0  Los CA Angeles
1            none
2          London
3          Dublin
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