0

I'm trying to search for a keyword in a dataframe and print the keyyword if found using the following code:

if df[df['description'].str.contains(keyword,case=False)]:
    print(keyword)
else:
    print("NOT FOUND") 

I'm getting the following error message:

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Any suggestions on how to fix this?

6
  • 1
    @BigBen that message is incomprehensible for beginners, usually. Commented Dec 9, 2021 at 21:23
  • 1
    Also, I think this might actually be a use for .any(). Usually it's better for the OP to change there code, but here... Commented Dec 9, 2021 at 21:26
  • 1
    yeah sometimes this place feels like the Q&A of Python 101 Commented Dec 9, 2021 at 21:28
  • @ZLi it can feel like that if you spend most of your SO time in the python tag...:) Commented Dec 9, 2021 at 21:42
  • @user17242583 I mean I feel there used to be good questions which requires some thinking and more than 1 line as an answer... Commented Dec 9, 2021 at 21:43

2 Answers 2

2

Try this instead:

if df['description'].str.contains(keyword,case=False).any():
    print(keyword)
else:
    print("NOT FOUND") 

df['description'].str.contains(keyword,case=False) returns a column, the same length as df['description'], containing True or False values, where each corresponds to the value of the same index in df['description']. If that value contained the keyword, the value in the returned Series is True, otherwise, False.

Calling .any() on a Series object will return True if at least one value in the Series is True. If all of them are False, .any() will return False.

Sign up to request clarification or add additional context in comments.

Comments

0

Your expression

df[df['description'].str.contains(keyword,case=False)]

Doesn't return a bool, it returns a subset of the original dataframe containing the rows that match the predicate (contains keyword). So as the error message implies you need to test if this dataframe is empty or not.

Comments

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.