如何在python中使用pandas以表格格式显示文本?

2024-04-26 21:14:59 发布

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

我有输出文本,格式为

标题1 URL1
标题1 URL2
标题1 URL3
title1 URL4
title1 URL5
title1 URL6

想用pandas将其显示为表吗

标题1 url1
url2
url3
url4
url5
url6


Tags: 文本标题pandas格式url1title1url2url3
1条回答
网友
1楼 · 发布于 2024-04-26 21:14:59

IIUC:你可以做的是:

from pandas.compat import StringIO
import pandas as pd
import numpy as np

text = '''title url
title1 URL1
title1 URL2
title1 URL3
title1 URL4
title1 URL5
title1 URL6'''

df = pd.read_csv(StringIO(text), sep='\s+')
#Drop duplicates by keeping first
df['title'] = df['title'].drop_duplicates(keep='first')
#Replace nan with white space
df = df.replace(np.nan, ' ', regex=True)
df.to_html('test.html')

输出如下:

enter image description here

相关问题 更多 >