【发布时间】:2020-11-29 22:18:00
【问题描述】:
我正在处理一个大熊猫数据框,它包含两列:
import pandas as pd
df = {'text': ['Expression of H-2 antigenic specificities on', 'To study the distribution of myelin-associated'],
'id': [1, 2]}
df = pd.DataFrame(df)
我想检查文本长度是否大于 2,然后将文本分成 2-2 个作品的块,如果长度小于 2,则不要选择取该行。
首先我选择了 len >= 2 的行:
df['len'] = df['text'].apply(lambda x: len(x.split()))
df = df[df['len']>2].reset_index(drop=True)
现在我想选择将文本分成 2 个单词的块并制作多行,如下所示(这是预期的输出):
text id
0 Expression of 1
1 H-2 antigenic 1
2 specificities on 1
3 To study 2
4 the distribution 2
5 of myelin-associated 2
有explode 方法,但我不知道在使用explode 方法时如何拆分成块?
df['text'] = df['text'].str.split()
df.explode('text')
给出(不是如上预期的输出):
text id
0 Expression 1
0 of 1
0 H-2 1
0 antigenic 1
0 specificities 1
0 on 1
1 To 2
1 study 2
1 the 2
1 distribution 2
1 of 2
1 myelin-associated 2
【问题讨论】:
-
你的预期输出是什么?
-
@BEN_YO 编辑了问题。
标签: python python-3.x pandas csv