Anne Goback
Anne Goback

Reputation: 27

pandas sort values of groupby

I have a set of data about football:

dataset

I sorted it by how many matches were played at each ground:

fb2 = fb.groupby(by=['Ground'])['Ground'].count()
print(fb2)

Output:

Ground
Aberdeen         11
Abu Dhabi        37
Adelaide         82
Ahmedabad        24
Albion            5
                 ..
Vijayawada        1
Visakhapatnam    11
Wellington       56
Whangarei         1
Worcester         3
Name: Ground, Length: 173, dtype: int64

Now I want to sort the results, in descending order of how many matches were played at each ground.

I am very new to python...any help would be much appreciated!

Upvotes: 0

Views: 4668

Answers (2)

Eric Truett
Eric Truett

Reputation: 3010

If you use named aggregation, you can specify a column name to sort on:

fb2 = (
  fb
  .groupby('Ground', as_index=False)
  .agg(n_matches=('Ground', 'count'))
  .sort_values('n_matches', ascending=False)
)

Upvotes: 4

Ynjxsjmh
Ynjxsjmh

Reputation: 30032

The type of fb.groupby(by=['Ground'])['Ground'].count() is Series, you can sort it using pandas.Series.sort_values()

fb.groupby(by=['Ground'])['Ground'].count().sort_values(ascending=False))

Upvotes: 3

Related Questions