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

标签 python pandas dataframe openpyxl

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

相关文章:

python - 减去数据框的最佳方法

python - 评估 Pandas DataFrame 中的 bool 表达式

python - pandas:groupby 和聚合而不会丢失分组的列

python - 替代 Pandas DataFrame 中的嵌套 np.where

python - 无法在Python 3中正确读取HTML数据

python - 如何调整 N 维 numpy 图像的大小?

python - 查找连续索引 pandas

python - 'dataframe' 对象没有属性 'str' 问题

python - Pandas 根据列值组合数据框

python - Hadoop:输出文件具有双输出