熊猫将数据框字典导出到Excel

时间:2020-10-16 13:57:37

标签: python excel pandas

嗨,我希望有人能帮助我。

我有一个很大的数据电子表格,我创建了一个“数据框字典”,但是现在我很难将其导出到一个excel文件中,每个数据框在excel文档中都有自己的工作表。由于其他人可以使用此文件,因此我也想使文件导出更灵活(它将是可单击的exe文件)

我查看了以下帖子以寻求帮助,但似乎无法理解:

Python - splitting dataframe into multiple dataframes based on column values and naming them with those values

Save list of DataFrames to multisheet Excel spreadsheet

我的代码如下:

# Sort the Dataframe
df.sort_values(by = 'Itinerary_Departure_Date')

#Seperate Bookings By Itinerary
df_dict = dict(iter(df.groupby('Itinerary_Departure_Date')))

filepath = filedialog.asksaveasfilename(defaultextension = 'xlsx')

def frames_to_excel(df_dict, path = 'filepath'):
    #Write dictionary of dataframes to separate sheets, within 1 file.

    writer = pd.ExcelWriter(path, engine='xlsxwriter')

    for tab_name, df_dict in df_dict.items():
        df_dict.to_excel(writer, sheet_name=tab_name)

    writer.save()

解决了!

走了另一个兔子洞!

#Seperate Bookings By Itinerary
dict_of_itin = {k: v for k, v in df.groupby('Itinerary_Departure_Date')}

#Chooseemptyexcelfromwhereeversaved
root = tk.Tk()
root.withdraw()

file_path = filedialog.askopenfilename()

book = load_workbook(file_path.replace('\\','/'))
writer = pd.ExcelWriter(file_path, engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

for df_name, df in dict_of_itin.items():
    df.to_excel(writer, sheet_name=df_name)

writer.save()

它依赖于使用它的人先保存一个空的电子表格,然后再将其写入。

不那么优雅,但可以! :D

克里斯

0 个答案:

没有答案