python-3.x - 将 pandas df 中的句子拆分为多行单词并对每个句子进行编号
问题描述
我是 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']
任何指针都非常感谢
解决方案
df = pd.DataFrame({'sn': [0,1],
'sent': [['an', 'apple', 'is', 'an', 'example', 'of', 'what?'], ['a', 'potato', 'is', 'an', 'example', 'of', 'what?']],
'ent': [['O', 'F', '0', '0', '0', 'O', 'O'], ['O', 'V', '0', '0', '0', 'O', 'O']]})
df.apply(pd.Series.explode).set_index('sn')
结果:
sent ent
sn
0 an O
0 apple F
0 is 0
0 an 0
0 example 0
0 of O
0 what? O
1 a O
1 potato V
1 is 0
1 an 0
1 example 0
1 of O
1 what? O
推荐阅读
- python - 三元运算:“系列的真值不明确”错误
- java - 使用 Java 8 另存为打印到 pdf 选项
- javascript - 我可以导入一个模块而不在 JavaScript 中执行它吗?
- python - 将 xml 元素的生成器转换为列表会产生未关闭的令牌错误
- python - After() 和 destroy() 在 if 语句中不起作用
- android - 在 android 上读取 CSV 文件会导致奇怪的字符
- security - 在上传之前检查二进制文件是否安全
- flutter - 无法在 Flutter 中下载文件
- mysql - 这个 SQL 查询会返回什么?
- javascript - Vuetify 动态绑定属性