How to use “Named aggregation” [duplicate]

拥有回忆 提交于 2021-02-02 09:51:07

问题


I want to apply two different aggregates on the same column in a pandas DataFrameGroupBy and have the new columns be named.

I've tried using what is shown here in the documentation. https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#named-aggregation

In [82]: animals.groupby("kind").agg(
   ....:     min_height=('height', 'min'),
   ....:     max_height=('height', 'max'),
   ....:     average_weight=('weight', np.mean),
   ....: )
   ....: 
Out[82]: 
      min_height  max_height  average_weight
kind                                        
cat          9.1         9.5            8.90
dog          6.0        34.0          102.75

Something like what I'm trying to do is:

df = pd.DataFrame({"year": [2001, 2001, 2001, 2005, 2005],
                   "value": [1, 2, 5, 3, 1]})

df = df.groupby("year").agg(sum=('value', 'sum'),
                            count=('value', 'size'))

However, this gives the following:

TypeError: aggregate() missing 1 required positional argument: 'arg'

回答1:


Since you need two aggfunction for one columns , you may need to pass to list like when you are not update your pandas to 0.25.0

df = df.groupby("year").value.agg(['sum','count'])
df
      sum  count
year            
2001    8      3
2005    4      2 

In pandas 0.25.0

pd.__version__
'0.25.0'
df = df.groupby("year").agg(sum=('value', 'sum'),
                            count=('value', 'count'))
df
      sum  count
year            
2001    8      3
2005    4      2


来源:https://stackoverflow.com/questions/57127632/how-to-use-named-aggregation

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