【发布时间】:2021-08-23 02:31:38
【问题描述】:
我想标记位于 pandas 数据框中的句子。正如您在示例中看到的那样,一些句子被分成多行(这些是来自 srt 文件的字幕,我最终希望将其翻译成不同的语言,但首先我需要将它们放在一个单元格中)。句末由句末句号决定。我想创建一个类似于列句的列,我为每个句子编号(不一定是字符串,也可以是数字)
values=[
['This is an example of subtitle.','sentence_1'],
['I want to group by sentences, which','sentence_2'],
['the end is determined by a period.','sentence_2'],
['row 0 should have sentece_1, rows 1 and 2 ','sentence_3'],
['should have sentence_2.','sentence_2'],
['and this last row should have sentence_3.','sentence_3']
]
df=pd.DataFrame(values,columns=['subtitle','sentence_number'])
df['presence_of_period']=df.subtitle.str.contains('\.')
df
output:
subtitle sentence_number presence_of_period
0 This is an example of subtitle. sentence_1 True
1 I want to group by sentences, which sentence_2 False
2 the end is determined by a period. sentence_2 True
3 row 0 should have sentece_1, rows 1 and 2 sentence_3 False
4 should have sentence_2. and this sentence_3 True
5 last row should have sentence_3. sentence_4 True
我如何创建 sentence_number 列,因为它必须读取 subtitle 列上的先前单元格?我在考虑一个窗口函数或 shift() 但不知道如何使它工作。我添加了一列来显示单元格是否有句点,表示句子的结尾。另外,如果可能的话,我想将“and this”从第 4 行移到第 5 行的开头,因为它是一个新句子(不确定这是否需要不同的问题)。
有什么想法吗?
【问题讨论】:
标签: python pandas window-functions