首页 > 解决方案 > 继续索引而不是在 Python 中重新开始

问题描述

我有一个问题,我很难找到解决方案。

我需要阅读多个制表符分隔的文档。每个文档中的一列包含表单上的句词索引 (1-1, 1-2,...,1-11, 2-1...) 等。对于我的任务,我需要组合多个文档到 NLP 任务的列表中。这没有问题。但是,这意味着当列表中有新文档时,句子索引自然会从 (1-1) 开始。我希望编写一个继续计算句子的函数,而不管它是一个新文档。

也就是说,而不是例如 (61-10, 61-11, 1-1, 1-2...),我希望有 (61-10, 61-11, 62-1, 62-2.. 。) 等等。单词索引不是那么重要,所以只有句子索引的解决方案就可以了!(即(61、61、62、62,...)。

到目前为止,我已经尝试了一种解决方案,即在列表中隔离句子索引,如下所示,但我不知道如何继续。df是熊猫df。

sentence = []
for i, ind in enumerate(df["Sectionindex"]):
    sent = re.search('(.+?)-\d+', ind)
    sentence.append(int(sent.group(1)))

希望我的问题足够清楚,我对python比较陌生。

提前致谢。

标签: pythonpandasindexing

解决方案


如果我理解正确,您可以通过计算句点来生成一个句子计数器str.count('\.')(尽管通过假设每个句点对应一个句子,这确实会过度计算句子)。

然后句子索引将是cumsum()句子计数器的移位(加1,因为python是0索引)。

玩具示例:

df = pd.DataFrame({'id': [24, 30, 11], 'text': ['this is a sentence. this is another.', 'hello. welcome to stack overflow.', 'this is another sentence.']})

#    id                                  text
# 0  24  this is a sentence. this is another.
# 1  30     hello. welcome to stack overflow.
# 2  11             this is another sentence.
df['sentence'] = df['text'].str.count('\.').cumsum().shift(fill_value=0).add(1)

#    id                                  text  sentence
# 0  24  this is a sentence. this is another.         1
# 1  30     hello. welcome to stack overflow.         3
# 2  11             this is another sentence.         5

推荐阅读