Kavya shree
Kavya shree

Reputation: 448

How to display text in table format using pandas in python?

I have output text, which is of form

title1 URL1
title1 URL2
title1 URL3
title1 URL4
title1 URL5
title1 URL6

want to display it as table using pandas

title1 url1
      url2
      url3
      url4
      url5
      url6

Upvotes: 1

Views: 2548

Answers (1)

Abbas
Abbas

Reputation: 4070

IIUC: Here is what you can do:

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

You shall get the output as following:

enter image description here

Upvotes: 3

Related Questions