0

Also NOTE: This post doesn't answer my question: Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

I am using str.contains() the following way:

df1['company'] = ""
search = ['Inc.','Company','Ltd','Co.']
if(df1['fu'].str.contains('|'.join(search), na=False)):
    df1["company"] = "Yes"
else:
    df1['company'] = "No"

While df1['fu'].str.contains('|'.join(searchfor), na=False) works by itself, (i.e. it prints True/False values), the code written above throws a value error

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

What is confusing is that the df1['fu'].str.contains('|'.join(searchfor), na=False) does return boolean values.

NOTE: I do not want to use .all() or .any() because I want an element wise Truth/False instead of on the entire set.

AMC
  • 2,642
  • 7
  • 13
  • 35
Baby_Coder
  • 17
  • 4
  • 1
    Does this answer your question? [Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()](https://stackoverflow.com/questions/36921951/truth-value-of-a-series-is-ambiguous-use-a-empty-a-bool-a-item-a-any-o) – AMC Jul 10 '20 at 19:29
  • _Also NOTE: This post doesn't answer my question:_ Simply stating that doesn't make it true, can you elaborate? Also, please provide a [mcve], as well as the entire error output. – AMC Jul 10 '20 at 19:30

1 Answers1

0

df1['fu'].str.contains('|'.join(search), na=False) returns a Series which does not support the if statement because creating Series always returns a Series object, empty or not.

To answer your question;

# fill data-frame with True and False
df['company'] = df1['fu'].str.contains('|'.join(searchfor), na=False)

# replace True/False with 'yes'/'no'
# Note: True == 1 and False == 0
df['company'] = df['company'].apply(lambda x: ('no', 'yes')[x])

# as a one-liner 
df['company'] = ( df1['fu'].str.contains('|'.join(searchfor), na=False)
                  .apply(lambda x: ('no', 'yes')[x]) )
Sy Ker
  • 2,047
  • 1
  • 4
  • 20
  • _returns a Series which does not support the if statement because creating Series always returns a Series object, empty or not._ What, can you expand on what? – AMC Jul 10 '20 at 19:31