问题
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