Home > Back-end >  creating new column based on the fact whether at least 1 of multiple columns contains value from the
creating new column based on the fact whether at least 1 of multiple columns contains value from the

Time:01-31

I am trying to create a column which will have True/Falses or 1/0 based on the fact whether at least one of the N columns contains values from the list

I do it in the following way

list = ['apple', 'banana', 'orange']
df['new'] = df['One'].isin(mylist) | df['Two'].isin(mylist).... |df['N'].isin(mylist) 

Is there a faster way to write condition to evaluate that I have "True" in a new column if at least one the N columns contains a value?

I tried to do

cols = ['One',...'N']
df['new'] = df[cols].isin(mylist)

But it does not work

CodePudding user response:

You are close, need DataFrame.any for test if at least one True per row:

df['new'] = df[cols].isin(mylist).any(axis=1)
  • Related