Josh
Josh

Reputation: 3

Using iloc[x,y].str to call contains() on a specific dataframe value

Why can't I do iloc[x,y].str on a single value?

I'd like to be able to test if a specific value in a dataframe, accessed via iloc[x,y], contains a specific string.

I've seen documentation for finding NaN, but not actual strings.

keyword = 'test'

if df.iloc[1,2].str.contains(keyword,case=False):
   print('yes')

Instead of returning True and printing 'yes', instead I receive an error:

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

Is there another way to test a specific cell?

Upvotes: 0

Views: 3256

Answers (2)

ruby-lemon917
ruby-lemon917

Reputation: 86

Try:

keyword = 'test'
if df.iloc[1,2].find(keyword) == 0:
     print('yes')

Upvotes: 0

Parijat Bhatt
Parijat Bhatt

Reputation: 674

It happens because python string type has no method called contains while pandas.Series has a str.contains method.

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html

If you want to check whether a particular substring is contained in it, you could do like print(substring in df.iloc[x,y] ) which uses the 'in' functionality

Upvotes: 1

Related Questions