简体   繁体   English

如何在 python 中的 dataframe 中找到 substring

[英]How to find substring in dataframe in python

I would like to find a substring "sam" in the dataframe "df1".我想在 dataframe “df1”中找到一个 substring “sam”。 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. output 给出如下错误。 Please help.请帮忙。

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

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

Your line你的线路

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

Is close to be fine.接近就好了。 First you can convert the DataFrame to a string:首先,您可以将 DataFrame 转换为字符串:

df1.__str__()

And then check if "sam" is in the string然后检查“sam”是否在字符串中

result = "sam" in df1.__str__()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM