Rhubarb
Rhubarb

Reputation: 308

Sort/"ORDER BY" Equivalent in Pandas Python GroupBy Object, Aggregate

I've looked everywhere and haven't quite been able to find a clear solution that worked for me. Suppose I have the following table:

    Company or Agency                                       Records Exposed
                                                    count   sum
0   1-800-Flowers.com                               1       Unknown
1   21st Century Oncology                           1       2,213,597
2   37th Parallel Properties Investment Group, LLC  1       Unknown
3   4D Sound Diagnostics                            1       1,000
4   7-Eleven, Inc.                                  1       7,832

Generated with the following query:

companies = data.groupby('Company or Agency')
companies = companies.agg({'Records Exposed': np.sum, 'Company or Agency' : ['count']})
companies = companies.reset_index()
companies = pd.DataFrame(companies)
#companies.sort_values('Company or Agency')
companies.head()

Basically, I want to sort my DataFrame based on the column 'Company or Agency count.' How can I do this?

Upvotes: 1

Views: 53

Answers (1)

Yaniv
Yaniv

Reputation: 829

It looks like the agg function created a MultiIndex. One way to refer to the headers of a multi-indexed DataFrame is by tuples, so all in all it should be as simple as:

companies.sort_values(by=('Company or Agency', 'count'))

Upvotes: 1

Related Questions