python - Pandas 创建数据透视表时出错(KeyError)

标签 python pandas pivot-table keyerror

我正在尝试使用 Pandas 从 Dataframe 创建数据透视表。下面给出的是我的数据框的 View 。

category,date,type1,type2,total
PROD_A,2018-10-01,2,2,4
PROD_A,2018-10-02,2,0,2
PROD_B,2018-10-01,0,0,0
PROD_A,2018-10-03,0,0,0

我正在尝试创建一个数据透视并将输出保存到 Excel 文件

Summary = pd.pivot_table(df, values=['total'], index=['category'], columns='date')

Summary.to_excel(writer, sheet_name='Summary')

我收到以下错误

KeyError : 'total'

任何人都可以指导我我哪里出了问题吗?谢谢

更新数据类型:

category   object
date       object
type1      int64
type2      int64
total      float64
dtype:     object

df.head() 的输出:

category,date,type1,type2,total
PROD_A,2018-10-01,2,2,4
PROD_A,2018-10-02,2,0,2
PROD_B,2018-10-01,0,0,0
PROD_A,2018-10-03,0,0,0
PROD_B,2018-10-03,2,3,5

最佳答案

问题是['total'],它在列中创建MultiIndex:

Summary = pd.pivot_table(df, values=['total'], index=['category'], columns='date')

print (Summary)

              total                      
date     2018-10-01 2018-10-02 2018-10-03
category                                 
PROD_A          4.0        2.0        0.0
PROD_B          0.0        NaN        NaN

解决方案是使用删除它:

Summary = pd.pivot_table(df, values='total', index='category', columns='date')
print (Summary)
date      2018-10-01  2018-10-02  2018-10-03
category                                    
PROD_A           4.0         2.0         0.0
PROD_B           0.0         NaN         NaN

最后将索引转换为列 reset_index :

Summary = (pd.pivot_table(df, values='total', index='category', columns='date')
             .reset_index(drop=True))
print (Summary)
date  2018-10-01  2018-10-02  2018-10-03
0            4.0         2.0         0.0
1            0.0         NaN         5.0

关于python - Pandas 创建数据透视表时出错(KeyError),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52776285/

相关文章:

excel - 显示源数据中不存在的标签的数据透视表

python - 在 python 中使用 heapq 获取优先级列表时出现问题

python - 值错误 : invalid literal for int() with base 10: Python

python - 编译 python 代码并将其链接到 C++ 程序?

python - 使用数据框绘制 vbar_stack

dataframe - 可在 Julia 的多个列中进行透视

python - 属性错误 : 'Series' object has no attribute 'notna'

python - 使用链接的 "join"连接多个数据帧(而不是合并或连接)是否有效?

python - 如何在 Pandas 中获得同一条船连续安装的最旧部分安装?

sql-server - 如何在 SQL Server 中同时使用 PIVOT 和 JOIN?