0

Here i am trying to access a (LanguageWorkedWith) column on a dataframe and filter it if it contains Python.

 df_18['LanguageWorkedWith'].apply(lambda x: x.str.contains('Python'))

but it keeps producing this error:

AttributeError                            Traceback (most recent call last)
<ipython-input-66-9cb9d7ffdfb2> in <module>
----> 1 df_18['LanguageWorkedWith'].apply(lambda x: x.str.contains('Python'))

~\anaconda3\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds)
   3846             else:
   3847                 values = self.astype(object).values
-> 3848                 mapped = lib.map_infer(values, f, convert=convert_dtype)
   3849 
   3850         if len(mapped) and isinstance(mapped[0], Series):

pandas\_libs\lib.pyx in pandas._libs.lib.map_infer()

<ipython-input-66-9cb9d7ffdfb2> in <lambda>(x)
----> 1 df_18['LanguageWorkedWith'].apply(lambda x: x.str.contains('Python'))

AttributeError: 'str' object has no attribute 'str'

I have used the str.contains() method on a different column before and it worked. I'd be glad to know why it worked for one and didn't work for the other.

  • Please try `df_18['LanguageWorkedWith'].str.contains('Python')`. You were applying a dataframe method to a pandas Series. – wwnde Nov 22 '20 at 00:15
  • thank you i get it. but i guess the method can also be used on a SeriesGroupBy object – Atimah Adavize Nov 22 '20 at 00:25
  • 1
    Does this answer your question? [Check if string is in a pandas dataframe](https://stackoverflow.com/questions/30944577/check-if-string-is-in-a-pandas-dataframe) – Bill Huang Nov 22 '20 at 00:28

1 Answers1

0

Use -

Option 1

df['Col1'].apply(lambda x: 'Python' in x)

Option 2

df_18['LanguageWorkedWith'].str.contains('Python')

Option 2 is a more pandas way of doing things and will be faster than apply

Vivek Kalyanarangan
  • 8,951
  • 1
  • 23
  • 42