python - Python Pandas 将文本包装在单元格中输出它 to_html
问题描述
我试图在某个点包装文本,例如|
在一个单元格中并将其导出到 html。
一个例子:
import pandas as pd
df = pd.DataFrame({'EmployeeId': ['157', '292', '643', '124', '355'],
'City': ['Mumbai|Bangalore', 'Pune|Mumbai|Delhi', 'Mumbai|Bangalore', 'Mumbai|Pune', 'Bangalore']})
print(df)
df.to_html('test1.html')
输出:
EmployeeId City
0 157 Mumbai|Bangalore
1 292 Pune|Mumbai|Delhi
2 643 Mumbai|Bangalore
3 124 Mumbai|Pune
4 355 Bangalore
我会有一个这样的 html 文件(预期):
输出:
EmployeeId City
0 157 Mumbai
Bangalore
1 292 Pune
Mumbai
Delhi
2 ... ...
任何帮助都感激不尽。
解决方案
基本上这个想法是使用str.split()
后跟explode()
. 像以下代码这样的东西应该会有所帮助。
(df.set_index(['EmployeeId']).apply(lambda x:x.str.split('|').explode()).reset_index())
输出就像
EmployeeId City
0 157 Mumbai
1 157 Bangalore
2 292 Pune
3 292 Mumbai
4 292 Delhi
5 643 Mumbai
6 643 Bangalore
7 124 Mumbai
8 124 Pune
9 355 Bangalore
推荐阅读
- javascript - 为什么我的 Promise 从模块导出中返回 main.js 中的未定义?
- signal-processing - 如何在倍频程中以不同的采样率同步传感器数据?
- azure-data-factory-2 - 借助 Azure 数据工厂活动检查文件编码
- javascript - 模块“AppModule”在 syntaxError 处导入的意外值“未定义”
- python - 如何在 Windows 上使用 PIL 打开 TIFF?
- r - 一个 R 程序在模拟一个公平的骰子后计算一个的数量
- angular - 更少的 CSS 导入在 Angular 7 中停止工作 - 如何修复它?
- python - 在递归调用期间附加列表项(最后我得到空列表)
- ios - 如何删除不再显示在 UIScrollView 中的内容
- python - 无法将命令绑定到按钮 Python 3.7