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'?
CodePudding user response:
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__()
CodePudding user response:
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