Combining column with list as data type

Viewed 24

I have a dataframe with column values such as below:

df:

I would like to combine all the values from column b into one list and remove duplicates.

Desired Output:

[Red, Blue, Green, Purple, Yellow]

So far I have tried using df['b].drop_duplicates().to_list() but am getting a list of lists as the output.

1 Answers

Try .explode():

from ast import literal_eval
df["b"] = df["b"].apply(literal_eval)

print(df["b"].explode().drop_duplicates().to_list())

Prints:

['Red', 'Blue', 'Green', 'Purple', 'Yellow']
Related