[英]Unable to write full pivot table to a new sheet in an existing excel workbook using pandas
I am able to write the pivot table generated a new sheet in an existing workbook, but when I open the excel file I dont see the indexes, I see only values.我能够编写 pivot 表在现有工作簿中生成一个新工作表,但是当我打开 excel 文件时,我看不到索引,我只看到值。 However I can see the complete pivot correctly in terminal.
但是我可以在终端正确地看到完整的 pivot。
I created this file:我创建了这个文件:
writer = pd.ExcelWriter('Output.xlsx')
I have this in a sheet in the above file created:我在上面创建的文件中的工作表中有这个:
lookup = pd.merge(ns,sfdc[['Account ID','Account Status']],on=['Account ID'],how='left')
lookup.to_excel(writer, sheet_name='latest_sg',index=False)
I did a pivot table:我做了一个 pivot 表:
pivot = lookup.pivot_table(index=['Account ID','accountname'],values=['gb'],aggfunc='sum',fill_value=0)
pivot.to_excel(writer, sheet_name='pivot', index=False)
writer.save()
in terminal I get the output for:在终端我得到 output 用于:
print(pivot)
gb
Account ID accountname
1-1 ABC Inc. 0
1-2 DEF 1
1-3 XYZ 974
1-4 TRX 00
But in the Output.xlsx I get a new sheet as 'pivot that gets created but the sheet has only GB column:但是在 Output.xlsx 中,我得到了一个新工作表作为“创建的枢轴,但工作表只有 GB 列:
gb
0
1
974
00
The excel sheet does not show complete pivot table details. excel 表未显示完整的 pivot 表详细信息。 Please help
请帮忙
There is problem MultiIndex
is removed in to_excel
, because index=False
parameter.在
MultiIndex
中删除了to_excel
存在问题,因为index=False
参数。
Correct solution is remove index=False
, but then possible empty row after header:正确的解决方案是删除
index=False
,但在 header 之后可能出现空行:
pivot.to_excel(writer, sheet_name='pivot')
Or convert MultiIndex
to columns by DataFrame.reset_index
and then not write default Rangeindex
with index=False
:或者通过
DataFrame.reset_index
将MultiIndex
转换为列,然后不使用index=False
写入默认Rangeindex
:
pivot.reset_index().to_excel(writer, sheet_name='pivot', index=False)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.