【发布时间】:2021-05-24 23:55:49
【问题描述】:
因此,我一直在关注这个网站,了解我的 Python 知识库。决定把我的第一个问题抛在脑后,所以希望有人能够帮助我。
我目前遇到以下问题: 尝试将 Pandas Pivot 表打印到预定义的 excel 模板中,例如从单元格 C5
代码如下,我通过 CSV 加载的表格也在那里
from openpyxl import Workbook
from openpyxl.compat import range
from openpyxl.utils import get_column_letter
from openpyxl import load_workbook
from openpyxl.styles import Alignment
from openpyxl.utils.dataframe import dataframe_to_rows
import pandas as pd
pnl_lst = pd.read_csv('data_test.csv', index_col=0)
pnl_lst = pd.DataFrame(pnl_lst, columns=['Fruit_Veg', 'Item', 'AmountSold','AmountRotten','#ofpickers'])
pnl_lst = pnl_lst.groupby('Fruit_Veg').apply(lambda x: x.pivot_table(index=['Item'],aggfunc='sum',margins=True,margins_name='Total'))
print(pnl_lst)
通过 data_test.csv 输入表格
| Fruit_Veg | Item | AmountSold | AmountRotten | #ofpickers | |
|---|---|---|---|---|---|
| 1 | Fruit | Apple | 0.907502 | 0.176108 | 0.365398 |
| 2 | Veg | Carrot | 0.707491 | 0.644805 | 0.375513 |
| 3 | Fruit | Pear | 0.898554 | 0.724919 | 0.338557 |
| 4 | Fruit | Raspberry | 0.284849 | 0.023705 | 0.80169 |
| 5 | Veg | Potato | 0.205464 | 0.682219 | 0.834467 |
| 6 | Veg | Aubergine | 0.644248 | 0.531195 | 0.970782 |
生成的输出(表格变得奇怪,但第一列中的 Fruit 和 Veg 是合并的单元格):
| Fruit_Veg | Item | #ofpickers | AmountRotten | AmountSold |
|---|---|---|---|---|
| Fruit | Apple | 0.365398283 | 0.176107564 | 0.907502485 |
| Pear | 0.338556856 | 0.724919365 | 0.898554328 | |
| Raspberry | 0.801690277 | 0.02370525 | 0.284848945 | |
| Total | 1.505645416 | 0.924732179 | 2.090905758 | |
| Veg | Aubergine | 0.970782439 | 0.531195328 | 0.644248183 |
| Carrot | 0.375513124 | 0.644804957 | 0.707491361 | |
| Potato | 0.834466661 | 0.682219111 | 0.20546385 | |
| Total | 2.180762224 | 1.858219396 | 1.557203394 |
尝试过的想法(遗憾的是没有运气):
- 我可以使用 XlsxWriter 打印 pandas 数据透视表,但这是写入单独的 excel 文件,而不是我需要的模板;
- 使用 Openpyxl 将数据透视表写入 excel 模板,但没有运气,因为格式完全错误,它无法将数据透视表转换为模块随后写入的可读内容;
- 尝试使用 pandas GroupBy 函数复制我的数据透视表。根据上面的输出,我不太清楚如何让 Totals 出现在每个 Fruit_Veg 部分下。
有人有什么明智的想法吗?
非常感谢!
【问题讨论】:
-
如果不想合并单元格,可以尝试在 groupby 操作中使用 'as_index' 参数指定。 IE; groupby('Fruit_Veg',as_index=False)
-
@Boskosnitch 谢谢。我认为这里的关键问题不是合并,主要是写入 excel 模板。如果您认为合并的单元格是导致此问题的原因,那么我也可以尝试一下。
标签: python excel pandas openpyxl xlsxwriter