Gin*_*ead 7 python-3.x pandas pandas-groupby
我对熊猫很陌生,并试图使用groupby. 我有一个多列的 df。
col1分组,然后对每个组进行排序col5,然后执行reset_index以获取数据帧的所有行。AttributeError: Cannot access callable attribute 'reset_index' of 'DataFrameGroupBy' objects, try using the 'apply' method。我的输入数据框:
col1 | col2 | col3 | col4 | col5
=================================
A | A1 | A2 | A3 | DATE1
A | B1 | B2 | B3 | DATE2
Run Code Online (Sandbox Code Playgroud)
我的代码:
df.sort_values(['col5'],ascending=False).groupby('col1').reset_index()
Run Code Online (Sandbox Code Playgroud)
如果groupby需要一些聚合函数,例如mean, sum, max:
df.sort_values(['col5'],ascending=False).groupby('col1').mean().reset_index()
Run Code Online (Sandbox Code Playgroud)
或者:
df.sort_values(['col5'],ascending=False).groupby('col1', as_index=False).mean()
Run Code Online (Sandbox Code Playgroud)