标记文本并为数据框中的每一行创建更多行 [英] Tokenise text and create more rows for each row in dataframe

查看:36
本文介绍了标记文本并为数据框中的每一行创建更多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 pythonpandas 来做到这一点.

I want to do this with python and pandas.

假设我有以下内容:

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

所以我希望每个文件的文本在每个句号处被拆分,并为这些文本的每个标记创建新行.

So I want the text of each file to be splitted at every fullstop and to create new lines for each of the tokens of these texts.

最有效的方法是什么?

推荐答案

使用:

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 原版.

First use DataFrame.pop for extract column, remove last . by Series.str.rstrip and split by with Series.str.split with escape . because special regex character, reshape by DataFrame.stack for Series, DataFrame.reset_index and rename for Series for DataFrame.join to original.

这篇关于标记文本并为数据框中的每一行创建更多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆