Python将文本包装在单元格中,并将其输出到html

2024-09-28 03:24:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在某个点包装文本,例如在单元格中的|,并将其导出为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文件(预期):

Image

输出:

   EmployeeId  City
0  157        Mumbai
              Bangalore 
1  292        Pune
              Mumbai
              Delhi
2  ...         ...  

任何帮助都将不胜感激


Tags: 文本importcitydataframepandasdfhtmlas
3条回答

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

非常感谢你的帮助

我试着这样做。我相信有更好的代码

import pandas as pd # Import the data
df = pd.DataFrame({'EmployeeId': ['157', '292', '643', '124', '355'],
                   'City': ['Mumbai|Bangalore', 'Pune|Mumbai|Delhi', 'Mumbai|Bangalore', 'Mumbai|Pune', 'Bangalore']})
#print(df)

df1 = df["City"].str.split("|", expand=True).stack().reset_index(level=1, drop=True)
#print(df1)

df2 = pd.concat([df, df1], axis=1, sort=False)
#print(df2)

df2 = df2.drop(["City"], axis=1)
#print(df2)

df2.loc[(df2["EmployeeId"].duplicated()  ), ["EmployeeId"]] = ''
df2.columns = ['EmployeeId', 'City New']
print(df2)

df2.to_html('test1.html')

输出:

  EmployeeId   City New
0        157     Mumbai
0             Bangalore
1        292       Pune
1                Mumbai
1                 Delhi
2        643     Mumbai
2             Bangalore
3        124     Mumbai
3                  Pune
4        355  Bangalore

将其导出到html时,我得到以下信息:

Image 1: With Grid

是否有任何方式可以在没有网格的情况下导出它(可能有样式)

Image 2: Without Grid

让我们做吧

yourdf=df.City.str.split('|').explode().to_frame('City').join(df[df.columns.difference(['City'])])
        City EmployeeId
0     Mumbai        157
0  Bangalore        157
1       Pune        292
1     Mumbai        292
1      Delhi        292
2     Mumbai        643
2  Bangalore        643
3     Mumbai        124
3       Pune        124
4  Bangalore        355

相关问题 更多 >

    热门问题