[英]Python pandas pivot_table margins keyError
考虑以下数据框:
test = pd.DataFrame({'A': [datetime.datetime.now(), datetime.datetime.now()], 'B': [1, 2]})
如果我使用如下所示的pivot_table
那么一切都很好:
test.pivot_table(index = 'A', aggfunc = {'B': 'mean'}, margins = True)
但是,如果我执行以下操作,则无法设置margins = True
(抛出错误KeyError: 'A'
):
test.pivot_table(index = test['A'], aggfunc = {'B': 'mean'}, margins = True)
我真的很困惑。 假设我需要做类似下面的事情并且需要设置margin = True
。 那不可能吗?
test.pivot_table(index = test['A'].dt.year, aggfunc = {'B': 'mean'}, margins = True)
尝试:
test['Ax']=test['A'].dt.year
test.pivot_table(index = 'Ax' , aggfunc = 'mean', values='B', margins = True)
输出:
B
Ax
2020 1.5
All 1.5
说明:如果您不传递values
,它将默认为df.columns
(数据df.columns
所有列,您正在旋转)。 https://github.com/pandas-dev/pandas/blob/v0.25.3/pandas/core/reshape/pivot.py#L87
所以从技术上讲,通过不传递任何values
您将所有列传递到values
,但同时仅提供一个函数,所以这就是这个KeyError
来源。
这里的来源与文档奇怪地不同: https : //pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.