[英]pandas group_by dataframe outputs only the aggregation column when written to excel; how to get the entire output on excel?
I am trying to group and sum-aggregate a specific column in my dataframe and then write this entire output to excel;我正在尝试对 dataframe 中的特定列进行分组和汇总,然后将整个 output 写入 excel; however, when i check the excel file after using the below code, it only contains the one aggregated column as the output and does not include any of the other grouping.
但是,当我在使用以下代码后检查 excel 文件时,它仅包含一个聚合列作为 output 并且不包括任何其他分组。 I am someone could help me correct the code or provide suggestions as to how to achieve this?
我有人可以帮助我更正代码或提供有关如何实现此目标的建议吗? Thanks in advance!
提前致谢!
my_df = pd.DataFrame(df.groupby(['Parent Category','Expense'])['Parent Category','Expense','Variance'].sum())
Next, I use the below code to write it to excel but it does not write the output into excel as in the image above接下来,我使用下面的代码将其写入 excel 但它不会将 output 写入 excel,如上图所示
writer = pd.ExcelWriter('Test.xlsx', engine = 'xlsxwriter')
my_df.to_excel(writer,sheet_name = '1', index = False)
writer.save()
why is the group by output not the same when written to excel?为什么output的组写入excel时不一样?
Can you please try the following?您可以尝试以下方法吗?
writer = pd.ExcelWriter('Test.xlsx', engine = 'xlsxwriter')
my_df.reset_index().to_excel(writer,sheet_name = '1', index = False)
writer.save()
Or if want to keep multi-index:或者如果想保留多索引:
writer = pd.ExcelWriter('Test.xlsx', engine = 'xlsxwriter')
my_df.to_excel(writer,sheet_name = '1', index = True)
writer.save()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.