2016-07-22 79 views
1

我想将我创建的数据透视表发送到工作簿中的新工作表上,但由于某种原因,当我执行我的代码时,表(表格被称为“Sheet1”)并且数据表被删除。在工作簿中的新工作表上创建熊猫数据透视表

这里是我的代码:

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

excel = pd.ExcelFile(filename) 
df = pd.read_excel(filename, usecols=['Product Description', 'Supervisor']) 

table1 = df[['Product Description', 'Supervisor']].pivot_table(index='Supervisor', columns='Product Description', aggfunc=len, fill_value=0, margins=True, margins_name='Grand Total') 



print table1 

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

另外,我有一点麻烦,我的数据透视表的设计。下面是数据透视表的样子:

enter image description here

我如何添加一个列到总结的每一行结束了吗?像这样的:(我只需要在最后一列,我不关心格式化一样,或任何)

enter image description here

+0

您能否包含代码的第一部分? – bernie

+1

用全功能更新了问题。 – Harrison

+0

@bernie我的数据透视表现在已经修复,但您认为您可以帮助我弄清数据透视表为何要删除数据表?我认为我发送了数据透视表来笨拙地表现出色。 – Harrison

回答

3

调用pivot_table()

演示时,只需使用margins=Truemargins_name='Grand Total'参数:

In [15]: df = pd.DataFrame(np.random.randint(0, 5, size=(10, 3)), columns=list('abc')) 

In [16]: df 
Out[16]: 
    a b c 
0 4 3 0 
1 1 1 4 
2 4 4 0 
3 2 3 2 
4 1 1 3 
5 3 1 3 
6 3 3 0 
7 0 2 0 
8 2 1 1 
9 4 2 2 

In [17]: df.pivot_table(index='a', columns='b', aggfunc='sum', fill_value=0, margins=True, margins_name='Grand Total') 
Out[17]: 
       c 
b    1 2 3 4 Grand Total 
a 
0    0.0 0.0 0.0 0.0   0.0 
1    7.0 0.0 0.0 0.0   7.0 
2    1.0 0.0 2.0 0.0   3.0 
3    3.0 0.0 0.0 0.0   3.0 
4    0.0 2.0 0.0 0.0   2.0 
Grand Total 11.0 2.0 2.0 0.0  15.0 
+1

Bam! +1 ...你也可以指定'margins_name ='Grand Total'' – bernie

+0

我会在哪里放置margin = True?此外,这将解决这个事实,我的Excel文件只包含数据透视表,而不是数据表了? – Harrison

+1

@bernie,好点,谢谢! :) – MaxU

相关问题