熊猫检查一行是否包含一个字符串而不是精确匹配

发布于 2025-02-13 16:23:48 字数 629 浏览 1 评论 0原文

我有以下功能来检查数据框中的一行是否包含一个字符串。但是,此方法确实有效,但是只有当提供的字符串与数据框中的字符串完全相同时,它才会匹配,并且在包含字符串时我需要匹配它。

例如,在“快速棕色狐狸”中搜索“ fox”将不产生返回,

def search_excel_files(file_list, search_term):
    #list of row indexes that contain the search term
    rows = {}
    for file in file_list:
        df = pd.read_excel("files/" + file)
        for row in df.iterrows():
            if search_term in row[1].values:
                #get row index
                row_index = row[0]
                #add row index to dictionary
                rows = df.iloc[row_index].to_dict()
    return rows

我该如何检查该行是否包含在本例中提供的字符串?

I have the following function to check if a row within a DataFrame contains a string. This approach does work however it will only match if the provided string is exactly the same as what is in the DataFrame and I need it to match if it contains a string.

e.g. searching for 'fox' in 'a quick brown fox' will yield no return

def search_excel_files(file_list, search_term):
    #list of row indexes that contain the search term
    rows = {}
    for file in file_list:
        df = pd.read_excel("files/" + file)
        for row in df.iterrows():
            if search_term in row[1].values:
                #get row index
                row_index = row[0]
                #add row index to dictionary
                rows = df.iloc[row_index].to_dict()
    return rows

How can I check if the row contains the provided string in this instance?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦毁影碎の 2025-02-20 16:23:48

在使用PANDA时,在列中思考比在行中更好,

df.your_col.str.contains("fox")

这将返回一系列布尔值,

下面每行的一个布尔,您将获得一个dataframe,其中每一行都在your_col列中具有FOX。

df[df.your_col.str.contains("fox")]

It's better to think in columns than in rows when using pandas

df.your_col.str.contains("fox")

which will return an array of booleans, one bool for each row

Below you will get a dataframe where each row has fox in your_col column.

df[df.your_col.str.contains("fox")]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文