How to refer to a column created by .agg() function in Pandas

Add Total column after groupby for avoid MultiIndex in columns and second proble need sorting by index, what is default value, so should be removed:

test = df.groupby('Sector')['Total'].agg(['sum', 'mean', 'count'])
#if use inplace=True cannot assign values
test.sort_values('sum', ascending = False, inplace = True)
print (test)
#if omitted, you need assign
test = test.sort_values('sum', ascending = False)
print (test)

Or if need custom columns names in named aggregations:

test = df.groupby('Sector').agg(sum1=('Total','sum'),
test.sort_values('sum1', ascending = False, inplace = True)
print (test)

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top