0

I have a dataframe with multiple columns, and one of them is named 'Message'. I am assigning a simple string to it 'test' on index 0

df['Message'][0] = "test"

Now I need to check it in IF statement and if there is a match, I want print the content index 0 of 'Time' column. Following is my code snippet:

if (df['Message'][0]).str.contains('test'):
    print(df['Time'][0])

For some reason I keep getting following error: AttributeError: 'str' object has no attribute 'str'

I have checked that type(df['Message'][0]) is returning as 'str'

Also the complete df shows up as following:

1
df.dtypes
Out[190]:
Date       object
Time       object
Col2       object
Col3       object
Message    object
dtype: object

Appreciate any help on what I am doing wrong here.

Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
Ad_noob
  • 73
  • 1
  • 9

1 Answers1

1

The str method/object is for a Pandas Series and not for an element of a Series even though that element is a string. By subscripting a series with [0] you are already getting an element of the series. Such string element has no object/property/method called str and hence the error.

To test an element contains a substring, you can use the syntax that @Andrej Kesely suggests:

if 'test' in df['Message'][0]:
SeaBean
  • 22,547
  • 3
  • 13
  • 25