Save pretty table output as a pandas data frame

Question:

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)])
print(prtab)

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

||

Answers:

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
# https://stackoverflow.com/a/18528589/190597 (Ofer)
# Use io.StringIO with Python3, use io.BytesIO with Python2 
output = io.StringIO()
df.to_csv(output)
output.seek(0)
print(pt.from_csv(output))

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

I found this method recently.

pretty_table.get_csv_string()

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)
text_file.close()
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.