我想用python
和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
因此,我希望每个句点都分割每个文件的文本,并为这些文本的每个标记创建新行。
最有效的方法是什么?
答案 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_index
和rename
适用于系列,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']