如何编写熊猫数据框,以及将图像或图表插入同一Excel工作簿中,但要使用多个工作表

时间:2019-03-04 19:31:15

标签: pandas

我已经从事上述任务已有一段时间了,但是我的代码没有按我预期的那样工作,因此,我希望从这个论坛中获得一些帮助。下面是我为此任务编写的代码片段:

###---------1st Visualization; Printing and Writing Results to An excel File 
for cust in Unique_cust_list:
    df_cust = miniBid_data[miniBid_data['Carrier_Code'] == cust]
    df_cust_lane = df_cust.groupby(['Mini_Bid_Date_2']).agg({'Lane_Id': 'sum'}).reset_index()
    df_cust_rank = df_cust.groupby(['Mini_Bid_Date_2']).agg({'Cost_Rank': 'mean'}).reset_index()
    df_cust_mer = pd.merge(df_cust_lane, df_cust_rank, how='inner', on='Mini_Bid_Date_2', copy=True)      
   figure = df_cust_rank.plot(kind='bar', x ='Mini_Bid_Date_2', y='Cost_Rank', legend=False, title=cust+" Carrier's Cost Ranking")
    fig = figure.get_figure()
    figSaved = fig.savefig(cust+'PPlot.png')

    # writing the multiple dataframes to worksheets using Pandas and XlsxWriter.
    # Create a Pandas Excel writer using XlsxWriter as the engine
    writer = pd.ExcelWriter('MiniBids_multiple_Results_Sample2.xlsx', engine='xlsxwriter')
    # Write each dataframe to a different worksheet.
    df_cust_mer.to_excel(writer, sheet_name=cust, index=False)
    workbook  = writer.book
    worksheet = writer.sheets[cust]
    ## insert the figure as image
    worksheet.insert_image('E1', 'figSaved')
    writer.save()

以下也是我使用的数据集的示例: a)“ miniBid_data” enter image description here

b)“ df_cust_rank”-由“ miniBid_data”为每个情节的“ Carrier_Code”创建的: enter image description here

C)“ df_cust_mer”-来自“ miniBid_data”的示例数据帧,已为每个“ Carrier_Code”写入excel:

enter image description here

我期望有一个工作簿(“ MiniBids_multiple_Results.xlsx”),每个“ Carrier_Code”都有几个选项卡(表),数据框显示在“ C”中,而从数据框绘制的各个图表则显示在“ B”中”。

但是,似乎代码每次都覆盖了信息。我很高兴在这个论坛上得到观众的帮助。预先谢谢你。

1 个答案:

答案 0 :(得分:0)

阅读代码后,似乎错误是由对象编写器造成的

我建议您像这样编写代码:(将编写器设置在循环之外)

writer = pd.ExcelWriter('MiniBids_multiple_Results_Sample2.xlsx', engine='xlsxwriter')

for cust in Unique_cust_list:
     :
     :
    ## insert the figure as image
    worksheet.insert_image('E1', 'figSaved')

writer.save()