Pandas pivot table aggregation with 'size' gives an error “'Series' object has no attribute 'columns'”

自作多情 提交于 2020-05-17 07:04:27

问题


I have the following DataFrame:

df = pd.DataFrame({'foo': [1, 3, 3, 4],
                   'bar': [2, 5, 8, 9],
                   'abc': [3, 7, 2, 4]})

When I tried using the command:

df.pivot_table('bar', 'foo', aggfunc='size')

I get the error:

AttributeError: 'Series' object has no attribute 'columns'

Strangely, the problem disappears when I aggregate several columns simultaneously:

df.pivot_table(['bar', 'abc'], 'foo', aggfunc='size')

But reappears again if I add the "dropna=False" parameter:

df.pivot_table(['bar', 'abc'], 'foo', aggfunc='size', dropna=False)

Expected output (that I do successfully get with the second command):

foo
1    1
3    2
4    1
dtype: int64

By the way, I'm using 'size' instead of 'count' on purpose, as I want to know the group sizes including the NaN values (even though it's not shown in this minimal example, because apparently the presence of NaNs is not necessary to trigger the error).

My version of pandas is 0.25.1. Can anyone explain this behavior?

来源:https://stackoverflow.com/questions/61465116/pandas-pivot-table-aggregation-with-size-gives-an-error-series-object-has-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!