How to get unique names from a column of dataframe

Viewed 181

I have a column (in a dataframe) that contains multiple city names and I need to know the unique name of cities.

        city
0      Dallas,Columbus,Portland,LasVegas
1      Columbus,Dallas,LasVegas
2      Dallas
3      Portland,Columbus,LosAngeles
4      Columbus

I want to obtain a list of cities like that: Dallas,Columbus,Portland,LasVegas,LosAngeles.

I tried to use countVectorize function and pandas unique() method but I am not sure how to do that.

2 Answers
df.city.str.split(",").explode().unique().tolist()

split the strings over "," which will give a list in each row. Then explode those lists to get a long series where each row has now one city name. Then take unique on them to get the distinct city names. Finally convert tolist to get:

['Dallas', 'Columbus', 'Portland', 'LasVegas', 'LosAngeles']

you can use str.split with .stack() and unique

df['city'].str.split(',',expand=True).stack().unique()

array(['Dallas', 'Columbus', 'Portland', 'LasVegas', 'LosAngeles'],
      dtype=object)
Related