Home > Mobile >  how to check if elements from each list in a column of liste are all the same
how to check if elements from each list in a column of liste are all the same

Time:04-22

I have a pd.dataframe where one column has lists, i need to create a new column that return true if all elements are equal or false if they are not

col1 col_lists
First [a,b,d]
Second [a,a]

this will be the desired outcome:

col1 col_lists new_col
First [a,b,d] False
Second [a,a] True

CodePudding user response:

Try this:

df.assign(new_col = df['col_lists'].map(lambda x: len(set(x)) == 1))

CodePudding user response:

Using list comprehension,

df["new_col"] = [True if len(set(l)) == 1 else False for l in df["col_lists"]]

The long way,

new_col = []

for l in df["col_lists"]:
  if len(set(l)) == 1:
    new_col.append(True)
  else:
    new_col.append(False)

df["new_col"] = new_col

Converting a list to a set allows us to get all the unique values from that list. If the set of that list has more than one value, then that would mean that the list doesn't have a single value for all its positions. So in that case, we set the value for the new column as False. Otherwise, we set it as True.

  • Related