All of these examples for using agg
work fine:
import pandas as pd
df = pd.DataFrame({"A":['A','A','B','B','B'],
"B":[1,2,1,1,2],
"C":[9,8,7,6,5]})
df.groupby('A')[['B','C']].agg({'B':'sum','C':'count'})
df.groupby('A')[['B','C']].agg({'B':['sum','count'],'C':'count'})
df.groupby('A')[['B']].agg('sum')
df.groupby('A')['B'].agg('sum')
This one throws a future warning as mentioned here:
df.groupby('A')['B'].agg({'B':['sum','count']})
This one works just fine:
df.groupby('A')[['B','C']].agg({'B':'sum'})
But this one throws an error (I'm aware this expression isn't necessary):
df.groupby('A')[['B']].agg({'B':'sum'})
SpecificationError: nested dictionary is ambiguous in aggregation
Why does it throw this error?
Output of pd.show_versions()
Comment From: TomAugspurger
Not sure, probably a bug. If you're interested in debugging further, let us know.
Comment From: stuarteberg
I can confirm in pandas 0.25.0.
These work fine:
In [27]: df = pd.DataFrame({'x': [1,1,2], 'y': [3,4,4]})
In [28]: df
Out[28]:
x y
0 1 3
1 1 4
2 2 4
In [29]: df.groupby('x').agg({'x': 'sum'})
Out[29]:
x
x
1 2
2 2
In [30]: df.groupby('y').agg({'x': 'sum'})
Out[30]:
x
y
3 1
4 3
But this raises an error:
In [31]: df.groupby('y')[['x']].agg({'x': 'sum'})
...
SpecificationError: nested dictionary is ambiguous in aggregation
And the .agg()
call only requires a single column, but you provide more than one column when you select columns from the groupby
, then you get a weird result. (Why does the result below include a y
column at all?)
In [34]: df.groupby('y')[['x', 'y']].agg({'x': 'sum'})
Out[34]:
x
x y
y
3 1 3
4 3 8
Comment From: SaiSridhar783
df.groupby('A')['B'].agg({'B':['sum','count']})
Here, the column 'B' is returned as a series so aggregation is not possible.
Comment From: mroeschke
Looks to work on master now. Could use a test
In [26]: import pandas as pd
...: df = pd.DataFrame({"A":['A','A','B','B','B'],
...: "B":[1,2,1,1,2],
...: "C":[9,8,7,6,5]})
In [27]: df.groupby('A')[['B']].agg({'B':'sum'})
Out[27]:
B
A
A 3
B 4
Comment From: talukder-sowrov
We are a university team looking for a good first issue.
Comment From: talukder-sowrov
Take