0

I would like to find a substring "sam" in the dataframe "df1". For example:

df1 = pd.DataFrame({'a': [1, 'sam right'], 'b': [7, 8]})
df2 = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
print(df1)
print(df2)
result = df1.str.contains("sam")
print("Result",result)
if result:
  print('*********Element exists in Dataframe************')
else:
  print('*********Element does not exists in Dataframe************')

output gives error as below. Please help.

 return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'str'. Did you mean: 'std'?

2 Answers 2

1

Your line

result = df1.str.contains("sam")

Is close to be fine. First you can convert the DataFrame to a string:

df1.__str__()

And then check if "sam" is in the string

result = "sam" in df1.__str__()
Sign up to request clarification or add additional context in comments.

Comments

1

Try this :

result = df1['a'].str.contains("sam")
if result.any():
    print('Element exists in Dataframe')
else:
  print('Element does not exists in Dataframe')
Element exists in Dataframe

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.