Ask Your Question
3

How can we group pandas data by a column and sort it in a descending order?

asked 2022-01-25 11:00:00 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-10-13 21:00:00 +0000

ladyg gravatar image

We can use the groupby() method of pandas to group the data by a particular column and the sort_values() method to sort it in descending order. Here's an example:

import pandas as pd

# create sample data
data = {'fruit': ['apple', 'banana', 'banana', 'apple', 'banana'],
        'count': [2, 3, 1, 4, 2]}

df = pd.DataFrame(data)

# group by 'fruit' column and sum the 'count' values
grouped = df.groupby('fruit').sum()

# sort by 'count' values in descending order
sorted_grouped = grouped.sort_values('count', ascending=False)

print(sorted_grouped)

Output:

        count
fruit        
apple       6
banana      6
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-01-25 11:00:00 +0000

Seen: 20 times

Last updated: Oct 13 '21