Dataframe using unique but the rows is a list not a "1d array-like"

Viewed 40

I have a dataframe that looks like:

import pandas as pd 
data = { 
    'Other':['A1', 'A2', 'A3', 'A4', 'A5'], 
    'category':[['Transfer'], ['Unknown'], ['Transfer','Facebook'], ['Facebook', 'Google', 'Other'], ['C3']]
} 
df = pd.DataFrame(data) 

I am trying to get a list of unique values for categories, unfortunately using

categories = df['category'].unique()

doesnt work, I am not sure what should be the approach to end with an outcome of

['Transfer', 'Unknown','Facebook','Google','Other','c3']
2 Answers

Let us try explode

df.category.explode().unique()
array(['Transfer', 'Unknown', 'Facebook', 'Google', 'Other', 'C3'],
      dtype=object)

If you need the unique list, you may use pd.unique on flatten of df.category using np.concatenate

l = pd.unique(np.concatenate(df.category))

Out[100]:
array(['Transfer', 'Unknown', 'Facebook', 'Google', 'Other', 'C3'],
      dtype=object)
Related