繁体   English   中英

Pandas 检查一行是否包含字符串而不是完全匹配

[英]Pandas check if a row contains a string rather than exact match

我有以下函数来检查 DataFrame 中的行是否包含字符串。 这种方法确实有效,但是只有在提供的字符串与 DataFrame 中的字符串完全相同时才会匹配,并且如果它包含字符串,我需要它来匹配。

例如,在“a quick brown fox”中搜索“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

在这种情况下,如何检查该行是否包含提供的字符串?

使用 pandas 时,最好在列中思考而不是在行中思考

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

这将返回一个布尔数组,每行一个布尔值

下面您将获得一个数据框,其中每一行在your_col列中都有狐狸。

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

暂无
暂无

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

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