2016-07-22 61 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

相關問題