Check if there are duplicates elements in a flat list contained in a pandas serie
Issue
One column of my dataframe contains lists.
I'm tring to compute a new column (element_unique) returning:
1if the list not contains duplicate element0if the list contains duplicate element
I managed to do this by iterating line by line using apply. I would like to know if there is a more efficient way to do this calculation without iterating line by line?
Input data
import pandas as pd
df = pd.DataFrame(data={
'key': ["A", "B", "C", "D"],
'dim': [["3", "1", "2"], [6, 5, 6], ["1"], ["2", "2"]]})
df
# key dim
# 0 A [3, 1, 2]
# 1 B [6, 5, 6]
# 2 C [1]
# 3 D [2, 2]
Calculation
def is_list_of_unique_values(list_):
if len(list_) == len(set(list_)):
return 1
return 0
df.loc[:, "element_unique"] = df["dim"].apply(is_list_of_unique_values)
df
# key dim element_unique
# 0 A [3, 1, 2] 1
# 1 B [6, 5, 6] 0
# 2 C [1] 1
# 3 D [2, 2] 0