gpt4 book ai didi

python - 在工作簿的新工作表上创建 pandas 数据透视表

转载 作者:太空宇宙 更新时间:2023-11-04 10:10:41 26 4
gpt4 key购买 nike

我正在尝试将我创建的数据透视表发送到工作簿中的新工作表上,但是,由于某种原因,当我执行代码时,会使用数据透视表创建一个新工作表(工作表称为“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

最佳答案

在调用 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

关于python - 在工作簿的新工作表上创建 pandas 数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38531670/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com