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