标记文本并为数据框中的每一行创建更多行

时间:2019-05-24 09:52:39

标签: python pandas tokenize

我想用pythonpandas来做到这一点。

让我们假设以下内容:

file_id   text
1         I am the first document. I am a nice document.
2         I am the second document. I am an even nicer document.

最后我要拥有以下内容:

file_id   text
1         I am the first document
1         I am a nice document
2         I am the second document
2         I am an even nicer document

因此,我希望每个句点都分割每个文件的文本,并为这些文本的每个标记创建新行。

最有效的方法是什么?

2 个答案:

答案 0 :(得分:1)

使用:

s = (df.pop('text')
      .str.strip('.')
      .str.split('\.\s+', expand=True)
      .stack()
      .rename('text')
      .reset_index(level=1, drop=True))

df = df.join(s).reset_index(drop=True)
print (df)
   file_id                         text
0        1      I am the first document
1        1         I am a nice document
2        2     I am the second document
3        2  I am an even nicer document

说明

首先使用DataFrame.pop提取列,最后用Series.str.rstrip删除最后一个.,然后用Series.str.split进行转义,并使用转义符.,因为特殊的正则表达式字符通过DataFrame.stack适用于系列,DataFrame.reset_indexrename适用于系列,DataFrame.join适用于原始版本。

答案 1 :(得分:0)

df = pd.DataFrame( { 'field_id': [1,2], 
                    'text': ["I am the first document. I am a nice document.",
                             "I am the second document. I am an even nicer document."]})

df['sents'] = df.text.apply(lambda txt: [x for x in txt.split(".") if len(x) > 1])
df = df.set_index(['field_id']).apply(lambda x: 
                                      pd.Series(x['sents']),axis=1).stack().reset_index(level=1, drop=True)
df = df.reset_index()
df.columns = ['field_id','text']