代码之家  ›  专栏  ›  技术社区  ›  Nabih Ibrahim Bawazir

在导出到excel的pandas数据框中给出标题

  •  0
  • Nabih Ibrahim Bawazir  · 技术社区  · 7 年前

    我有6个数据帧(命名为 a f ),我想导入到ms.excel中,为了便于阅读,我想给每个数据框打上标签,我试着 with cell notation ,但我得到了错误消息,这是我的代码:

    writer = pd.ExcelWriter('Summary Data Request 8 weeks.xlsx')
    a.to_excel(writer, sheet_name='Sheet1', startrow=1)
    b.to_excel(writer, sheet_name='Sheet1', startcol=7)
    c.to_excel(writer, sheet_name='Sheet1', startrow=11)
    d.to_excel(writer, sheet_name='Sheet1', startrow=11, startcol=6)
    e.to_excel(writer, sheet_name='Sheet1', startrow=21)
    f.to_excel(writer, sheet_name='Sheet1', startrow=21, startcol=6)
    writer.write('A1', 'Retail Kelontong')
    writer.write('G1', 'Pulsa')
    writer.write('A11', 'Minimarket')
    writer.write('G11', 'Retail dengan barcode')
    writer.write('A21', 'Retail dengan barcode 2')
    writer.write('G21', 'Food and Beverage')
    writer.save()
    

    以下是错误消息:

    AttributeError                            Traceback (most recent call last)
    <ipython-input-30-2354b95670c9> in <module>()
          6 e.to_excel(writer, sheet_name='Sheet1', startrow=21)
          7 f.to_excel(writer, sheet_name='Sheet1', startrow=21, startcol=6) 
    ----> 8 writer.write('A1', 'Retail Kelontong')
          9 writer.write('G1', 'Pulsa')
         10 writer.write('A11', 'Minimarket')
    
    
    AttributeError: '_XlsxWriter' object has no attribute 'write'
    

    我仍然不知道我做错了什么,我试着把作者改成 Sheet1 错误消息是

    name 'Sheet1' is not defined
    

    1 回复  |  直到 7 年前
        1
  •  2
  •   Jan Zeiseweis    7 年前

    根据文档,您必须使用 write 工作表的方法,而不是作者:

    writer = pd.ExcelWriter('Summary Data Request 8 weeks.xlsx')
    a.to_excel(writer, sheet_name='Sheet1', startrow=1)
    b.to_excel(writer, sheet_name='Sheet1', startcol=7)
    c.to_excel(writer, sheet_name='Sheet1', startrow=11)
    d.to_excel(writer, sheet_name='Sheet1', startrow=11, startcol=6)
    e.to_excel(writer, sheet_name='Sheet1', startrow=21)
    f.to_excel(writer, sheet_name='Sheet1', startrow=21, startcol=6)
    # Get sheet1
    sheet1 = writer.sheets['Sheet1']
    sheet1.write('A1', 'Retail Kelontong')
    sheet1.write('G1', 'Pulsa')
    sheet1.write('A11', 'Minimarket')
    sheet1.write('G11', 'Retail dengan barcode')
    sheet1.write('A21', 'Retail dengan barcode 2')
    sheet1.write('G21', 'Food and Beverage')
    writer.save()