【发布时间】: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