Save pretty table output as a pandas data frame


How to convert the output I get from a pretty table to pandas dataframe and save it as an excel file.

My code which gets the pretty table output

from prettytable import PrettyTable

prtab = PrettyTable()
prtab.field_names = ['Item_1', 'Item_2']
for item in Items_2:
       prtab.add_row([item, difflib.get_close_matches(item, Items_1)])

I’m trying to convert this to a pandas dataframe however I get an error saying DataFrame constructor not properly called! My code to convert this is shown below

AA = pd.DataFrame(prtab, columns = ['Item_1', 'Item_2']).reset_index()
Asked By: user7954765



Load the data into a DataFrame first, then export to PrettyTable and Excel:

import io
import difflib
import pandas as pd
import prettytable as pt

data = []
for item in Items_2:
    data.append([item, difflib.get_close_matches(item, Items_1)])
df = pd.DataFrame(data, columns=['Item_1', 'Item_2'])

# Export to prettytable
# (Ofer)
# Use io.StringIO with Python3, use io.BytesIO with Python2 
output = io.StringIO()

# Export to Excel file
filename = '/tmp/output.xlsx'
writer = pd.ExcelWriter(filename)
Answered By: unutbu

I found this method recently.


this will convert it to a csv string where you could write to a csv file.

I use it like this:

tbl_as_csv = pretty_table.get_csv_string().replace('r','')

text_file = open("output_path.csv", "w")
n = text_file.write(tbl_as_csv)
Answered By: Chris
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.