简体   繁体   中英

How to do sorting after groupby and aggregation on a Pandas Dataframe

I'm having a Pandas Dataframe and I'm doing a groupby on two columns and have a couple of aggregate functions on a column. Here is how my code looks like

df2 = df[X,Y, Z].groupby([X,Y]).agg([np.mean, np.max, np.min]).reset_index()

It find the aggregate functions on the column Z.

I need to sort by let's say min (ie sort_values('min') ) column but it keeps complaining that 'min' column does not exist. How can I do that

Since you are generating a pd.MultiIndex, you must use a tuple in sort_values.

Try:

df2.sort_values(('Z','amin'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM