2016-07-22 168 views
-1

我使用pandas/openpyxl来处理excel文件,然后创建数据透视表以添加到当前工作簿中的新工作表。当我执行我的代码时,会创建新工作表,但数据透视表不会添加到工作表中。将数据透视表写入excel文件时出现问题

这里是我的代码:

worksheet2 = workbook.create_sheet() 
worksheet2.title = 'Sheet1' 
workbook.save(filename) 

excel = pd.ExcelFile(filename) 
df = excel.parse(sheetname=0) 
df1 = df[['Product Description', 'Supervisor']] 

table1 = pd.pivot_table(df1, index = ['Supervisor'], 
          columns = ['Product Description'], 
          values = ['Product Description'], 
          aggfunc = [lambda x: len(x)], fill_value = 0) 



print table1 

writer = pd.ExcelWriter(filename) 
table1.to_excel(writer, 'Sheet1') 
writer.save() 
workbook.save(filename) 

当我打印出我的表,我得到这样的:

       <lambda>       \ 
Product Description EXPRESS 10:30 (doc) EXPRESS 10:30 (nondoc) 
Supervisor              
Building        0      1 
Gordon        1      0 
Pete         0      0 
Vinny A        0      1 
Vinny P        0      1 

                   \ 
Product Description EXPRESS 12:00 (doc) EXPRESS 12:00 (nondoc) 
Supervisor              
Building        0      4 
Gordon        1      2 
Pete         1      0 
Vinny A        1      1 
Vinny P        0      1 


Product Description MEDICAL EXPRESS (nondoc) 
Supervisor          
Building         0 
Gordon          1 
Pete          0 
Vinny A         0 
Vinny P         0 

我想数据透视表看起来像这样:(如果我的数据透视表的代码不会让它看起来像这样可以有人帮助我看起来像这样?我不知道如何添加总计列。它与数据透视表的aggfunc部分有关吗?)

enter image description here

+0

请提供完整的回溯。 –

+0

我做了一些修改。我不再有错误,但是,数据透视表并未被绘制。你能看看我对这个问题所作的编辑吗? – Harrison

+0

@Charlie Clark现在我的担心是1.为什么数据透视表不出现在表单上2.我怎样才能让我的数据透视表看起来像我提供的图像? – Harrison

回答

1

你不能这样做,因为openpyxl当前不支持数据透视表。有关更多信息,请参阅https://bitbucket.org/openpyxl/openpyxl/issues/295

+0

如果是这种情况,您推荐哪种工具可以执行表格旋转? –

+1

我建议您注册openpyxl邮件列表,以便获得发布公告,例如引入对数据透视表的支持的2.5a1版本。 –