标记文本并为datafram中的每一行创建更多的行

2024-04-27 19:32:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用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

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

最有效的方法是什么


Tags: 文件thetext文本anidpandasam
2条回答

用途:

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

解释:

首先对extract列使用^{},通过^{}删除最后一个.,并通过^{}和escape .进行拆分,因为特殊的正则表达式字符,对于Series,通过^{}重塑,对于Series,通过^{}rename重塑,对于^{}的Series,通过^{}rename重塑为原始

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']

相关问题 更多 >