[英]pandas pivot_table write to excel outputs empty sheet
It's just so strange.真是太奇怪了。
The pivot_table is definitely not empty. pivot_table 绝对不是空的。 When I print it out it shows everything without problem.当我打印出来时,它显示一切都没有问题。 But when I try to write it to_excel with ExcelWriter(or just to_excel), it gives me an almost empty sheet(with values only and nothing else).但是当我尝试用 ExcelWriter(或只是 to_excel)将它写入 to_excel 时,它给了我一个几乎是空的工作表(只有值,没有别的)。
Here's my code:这是我的代码:
result = df.pivot_table(
index=['Client Code','Client Name'],
values='Fiscal year',
aggfunc = lambda x: '/'.join(list(set(str(v) for v in x)))
)
writer = pd.ExcelWriter(f'resultnew.xlsx',mode='w',engine='openpyxl')
result.to_excel(writer,sheet_name='Data',index=False)
writer.save()
Hopefully there's someone can figure out what is problem.希望有人能找出问题所在。
I've figured it out myself.我自己想通了。 I just need to convert the pivot_table
to_records
and turn it to dataframe once again before export it to_excel
, and the output is perfect.我只需要将 pivot_table 转换为pivot_table
并再次将其转换为数据to_records
,然后再将其导出to_excel
,输出就完美了。 Simply change the codes like this:只需像这样更改代码:
pd.DataFrame(result.to_records()).to_excel(writer,sheet_name='Data',index=False)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.