[英]Python pandas pivot_table margins keyError
Consider the following dataframe:考虑以下数据框:
test = pd.DataFrame({'A': [datetime.datetime.now(), datetime.datetime.now()], 'B': [1, 2]})
If I use pivot_table
like below then everything is fine:如果我使用如下所示的
pivot_table
那么一切都很好:
test.pivot_table(index = 'A', aggfunc = {'B': 'mean'}, margins = True)
However, if I do the following, I can't set margins = True
(throws the error KeyError: 'A'
):但是,如果我执行以下操作,则无法设置
margins = True
(抛出错误KeyError: 'A'
):
test.pivot_table(index = test['A'], aggfunc = {'B': 'mean'}, margins = True)
I am really confused.我真的很困惑。 Let's say I need do something like below AND need to set
margin = True
.假设我需要做类似下面的事情并且需要设置
margin = True
。 Is that impossible?那不可能吗?
test.pivot_table(index = test['A'].dt.year, aggfunc = {'B': 'mean'}, margins = True)
Try:尝试:
test['Ax']=test['A'].dt.year
test.pivot_table(index = 'Ax' , aggfunc = 'mean', values='B', margins = True)
Outputs:输出:
B
Ax
2020 1.5
All 1.5
Explanation : in case if you don't pass values
it will default to df.columns
(all columns of dataframe, that you're pivoting over).说明:如果您不传递
values
,它将默认为df.columns
(数据df.columns
所有列,您正在旋转)。 https://github.com/pandas-dev/pandas/blob/v0.25.3/pandas/core/reshape/pivot.py#L87 https://github.com/pandas-dev/pandas/blob/v0.25.3/pandas/core/reshape/pivot.py#L87
So technically by passing no values
you were passing ALL columns into values
, yet at the same time providing function for just one, so this is where this KeyError
was coming from.所以从技术上讲,通过不传递任何
values
您将所有列传递到values
,但同时仅提供一个函数,所以这就是这个KeyError
来源。
Source here is oddly off with the documentation: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html这里的来源与文档奇怪地不同: https : //pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.