首页 > 解决方案 > 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  ...         ...  

任何帮助都感激不尽。

标签: pythonhtmlstringpandasdataframe

解决方案


基本上这个想法是使用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

推荐阅读