如何将我从漂亮表中获得的输出转换为pandas数据框并将其另存为excel文件。
我的代码获得漂亮的表格输出
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)
我正在尝试将其转换为pandas数据框,但是出现一条错误消息,提示 DataFrame构造函数未正确调用!我的代码将如下所示
AA = pd.DataFrame(prtab, columns = ['Item_1', 'Item_2']).reset_index()
答案 0 :(得分:0)
首先将数据加载到DataFrame中,然后导出到PrettyTable和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')