【问题标题】:How to display text in table format using pandas in python?如何在 python 中使用 pandas 以表格格式显示文本?
【发布时间】:2018-11-05 05:25:36
【问题描述】:

我有输出文本,格式为

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

想使用 pandas 将其显示为表格

title1 url1
      url2
     url3
    url4
     url5
     url6

【问题讨论】:

  • 你的意思是列名 = 'title',值为 url1 - url6?
  • 输出文本的类型是什么?是字符串还是熊猫数据框?
  • @bakka 列是title和url,每个title都有很多url
  • @AkshayNevrekar 输出为 json 格式

标签: python pandas dataframe multiple-columns rows


【解决方案1】:

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')

你会得到如下输出:

【讨论】:

    猜你喜欢
    • 2020-09-20
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    • 2011-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多