Error: Series' object has no attribute 'contains'"

Viewed 31155

I search on all columns (except the first) of my DataFrame and add a new column 'Matching_Columns' with the name of the matching column, When I try to remove all dots before testing if my pattern is contained within a row I receive an error.

This works:

keyword='123456789'
f = lambda row: row.apply(str).str.contains(keyword ,na=False, flags=re.IGNORECASE)
df1 = df.iloc[:,1:].apply(f, axis=1)

df.insert(loc=1, column='Matching_Columns', value=df1.dot(df.columns[1:] + ', ').str.strip(', '))

This gives me an error:

keyword='123456789'
f = lambda row: row.apply(str).str.replace(".","").contains(keyword ,na=False, flags=re.IGNORECASE)
df1 = df.iloc[:,1:].apply(f, axis=1)

df.insert(loc=1, column='Matching_Columns', value=df1.dot(df.columns[1:] + ', ').str.strip(', '))

Error:

AttributeError: ("'Series' object has no attribute 'contains'", 'occurred at index 0')

I can't figure out what's wrong with this. It looks like the str.replace(".","") is causing the error.

Any help would be appreciated

1 Answers

It should be str.contains because contains is an accessor of str not series.

So, to explain this better, str.replace returns a series object. You have injected contains function to series. That's why you are getting the error 'Series' object has no attribute 'contains'

f = lambda row: row.apply(str).str.replace(".","").str.contains(keyword ,na=False, flags=re.IGNORECASE)
Related