【发布时间】:2020-08-26 15:02:28
【问题描述】:
我是 python 新手,我有一个如下所示的 pandas 数据框:
df =
sn sent ent
0 ['an', 'apple', 'is', 'an', 'example', 'of', 'what?'] ['O', 'F', '0', '0', '0', 'O', 'O']
1 ['a', 'potato', 'is', 'an', 'example', 'of', 'what?'] ['O', 'V', '0', '0', '0', 'O', 'O']
我想创建另一个如下所示的 pandas 数据框:
newdf=
sn sent ent
0 an O
apple F
is O
an O
example O
of O
what? O
1 a O
potato V
is O
an O
example O
of O
what? O
我尝试了这段代码,最终得到了代码下方显示的内容
df.set_index('sn')
.stack()
.str.split(expand=True)
.stack()
.unstack(level=1)
.reset_index(level=0, drop=0)
这很接近我想要的,但似乎可以弄清楚其余的
sn sent ent
0 ['an', ['O',
0 'apple', 'F',
0 'is', 'O',
0 'an', 'O',
0 'example', 'O',
0 'of', 'O',
0 'what?', 'O',
1 'a', 'O',
1 'potato', 'V',
1 'is', 'O',
1 'an', 'O',
1 'example', 'O',
1 'of', 'O',
1 'what?'] 'O']
非常感谢任何指针
【问题讨论】:
-
尝试用explode和concat结果~
-
你也可以试试explode+join
df.join([df[i].explode() for i in ['sent','ent']])
标签: python-3.x pandas split unnest