0

Let's say I have this df:

id words
1  ['apple', 'banana', 'grape']
2  ['apple', 'banana', 'chocolate']
3  ['grape', 'popcorn', 'chocolate']
4  ['grape', 'apple', 'popcorn']

How can I create a new column checking if 'chocolate' or 'popcorn' is inside each row-list. I've tried something like this but it didn't work:

sublist = ['chocolate', 'popcorn']

df['boolean_check'] = df['words'].isin(sublist).any()

also tried:

 df['boolean_check'] = np.where(df['words'].isin(sublist).any(), True, False)

expected result:

id words                             boolean_check
1  ['apple', 'banana', 'grape']      False
2  ['apple', 'banana', 'chocolate']  True
3  ['grape', 'popcorn', 'chocolate'] True
4  ['grape', 'apple', 'popcorn']     True

1 Answer 1

1

Try with explode

np.where(df['words'].explode().isin(sublist).any(level=0), True, False)
Sign up to request clarification or add additional context in comments.

1 Comment

No need for np.where() ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.