我想用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
所以我希望每个文件的文本在每个句号处被拆分,并为这些文本的每个标记创建新行。
执行此操作的最有效方法是什么?
用:
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
原始。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句