0

I'm trying to search in string in dataframe column by using contains

1.

for idx, row in df.iterrows():
  if(row['name'].str.contains('abc')):

the above code throw this error

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

2.

for idx, row in df.iterrows():
      if(row['name'].contains('abc')):

and the second code throw this error

AttributeError: 'str' object has no attribute 'contains'
1
  • 1
    You suspect that row should have the str attribute, but the computer says it does not. Before asking on SO, do dir(row) or print(type(row)) or print(row) to find out what you're getting. This is going to be very common in your programming career, and the sooner your instincts change from "Ask the world for the answer" to "Check and see if maybe I'm a clumsy meatbag for the 100th time this week, first," the faster you'll become a better programmer. meta.stackoverflow.com/questions/261592/… Commented May 29, 2019 at 16:04

3 Answers 3

3

row['name'] is a dictionary with the value being the string you are searching. To search in a vectorized way, you don't need to use iterrows():

df['name'].str.contains('abc') will return a boolean index because it uses the pandas Series string contains method.

At the row level (if this is what you want) just use in:

for idx, row in df.iterrows():
      if 'abc' in row['name']:
Sign up to request clarification or add additional context in comments.

Comments

1

row['Name'] will return a string not a pandas series so you can't use .str.contains Instead of looping row by row you can apply it to the whole column df['row'].str.contains('abc') This will return a series of type bool.

Comments

0

You should iterate over the columns to search for your string, i.e.:

for column in df.columns:
    df[column].str.contains('some_value')

I'm unsure how you're going to use this, but if you simply want to know if any of the rows in a column contain the string, you can use .any(). This will return True or False. While the code above returns you a series

for column in df.columns:
    df[column].str.contains('some_value').any()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.