【问题标题】:How to search for multiple search terms across multiple rows in a Pandas dataframe?如何在 Pandas 数据框中的多行中搜索多个搜索词?
【发布时间】:2021-05-31 07:27:54
【问题描述】:

所以我之前的更简化的问题在这里 - How to search for text across multiple rows in a pandas dataframe?

我想要做的基本上是能够将包含多个短语的文本文档提供给搜索,而不仅仅是单数单词,即“new jersey”等,然后在多行中搜索术语并输出表中的一个新列,如果术语和存在,则为“True”,如果不是,则为“False”。例如,这是我表格的一小部分,我想搜索“new jersey”和“grow up”,其中的单词位于不同的行中。

             subtitle        start          end  duration
14                new    71.986000    72.096000  0.110000
15             jersey    72.106000    72.616000  0.510000
16               grew    72.696000    73.006000  0.310000
17                 up    73.007000    73.147000  0.140000
18          believing    73.156000    73.716000  0.560000

到目前为止,感谢旧线程的帮助,这就是我所拥有的,terms.txt 是搜索词列表:

import re

search = [term.strip() for term in open("terms.txt").readlines()]
search = fr"({'|'.join(search)})"
text = " ".join(df["subtitle"])
end = df["subtitle"].apply(len).cumsum() + pd.RangeIndex(len(df))
start = end.shift(fill_value=-1) + 1
df["start"] = start.tolist()
df["end"] = end.tolist()
df["match"] = False

到目前为止一切正常:

for match in re.finditer(search, text, re.IGNORECASE):
    idx1 = df[df["start"] == match.start()].index[0]
    idx2 = df[df["end"] == match.end()].index[0]
    df.loc[idx1:idx2, "match"] = True

我收到错误消息:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-14-9f347152f616> in <module>
      1 for match in re.finditer(search, text, re.IGNORECASE):
----> 2     idx1 = df[df["start"] == match.start()].index[0]
      3     idx2 = df[df["end"] == match.end()].index[0]
      4     df.loc[idx1:idx2, "match"] = True

~/opt/anaconda3/lib/python3.8/site-packages/pandas/core/indexes/base.py in __getitem__(self, key)
   4099         if is_scalar(key):
   4100             key = com.cast_scalar_indexer(key, warn_float=True)
-> 4101             return getitem(key)
   4102 
   4103         if isinstance(key, slice):

IndexError: index 0 is out of bounds for axis 0 with size 0

有谁知道我该如何解决这个问题,或者我是否可以使用其他方法来获得所需的结果?感谢所有帮助,对于任何格式问题,我深表歉意,因为我是这里的新手。

【问题讨论】:

    标签: python pandas dataframe search


    【解决方案1】:

    有 2 列“开始”和“结束”。

    import re
    
    terms = [term.strip() for term in open("terms.txt").readlines()]
    word = df["subtitle"].str.strip()
    end = word.apply(len).cumsum() + pd.RangeIndex(len(df))
    start = end.shift(fill_value=-1) + 1
    text = " ".join(word)
    df["match"] = False
    
    for term in terms:
        for match in re.finditer(fr"\b{term}\b", text, re.IGNORECASE):
            idx1 = start[start == match.start()].index[0]
            idx2 = end[end == match.end()].index[0]
            df[idx1:idx2] = True
    

    输出:

    $ cat terms.txt
    new jersey
    hello
    
    >>> df
       id   subtitle   start     end  duration  match
    0  14        new  71.986  72.096      0.11   True
    1  15     jersey  72.106  72.616      0.51   True
    2  16       grew  72.696  73.006      0.31  False
    3  17         up  73.007  73.147      0.14  False
    4  18  believing  73.156  73.716      0.56  False
    

    【讨论】:

    • 感谢您的帮助,但不幸的是,我仍然遇到与上述相同的错误!
    • 您是仅在示例上还是在数据集上测试了这段代码?你的 Python 和 Pandas 版本是什么?也许你应该分享你的 excel 文件。
    • 我只尝试了这些数据。如何准确共享我的 Excel 文件?对不起,我真的是新来的!补充一点,它也是一个我真正使用的 JSON 文件。
    • 编辑:如果某些搜索词不符合表格中的确切措辞/标准,是否会出现问题?
    • 不,我已经尝试过不存在的术语并返回一个空数据框而不会引发错误。
    猜你喜欢
    • 2019-12-06
    • 2023-03-15
    • 2018-01-08
    • 2022-01-03
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-20
    • 1970-01-01
    相关资源
    最近更新 更多