Count and Sort with Pandas

Given a pandas dataframe, we have to group by two columns, which return a count of aggregation. We need to sort the max count value.
Submitted by Pranit Sharma, on October 13, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Problem statement

Suppose we are given a DataFrame for which we have grouped by two columns, which return a count of aggregation. We need to sort the max count value.

Count and Sort with Pandas

For this purpose, we will first create a DataFrame and then we will apply the groupby method on two columns and then sort the values of the result.

The groupby() method is a simple but very useful concept in pandas. By using groupby(), we can create a grouping of certain values and perform some operations on those values.

The groupby() method splits the object, applies some operations, and then combines them to create a group hence large amounts of data and computations can be performed on these groups.

Let us understand with the help of an example,

Python program to count and sort with Pandas

# Importing pandas package
import pandas as pd

# Importing calendar
import calendar

# Creating a Dictionary
d = {
    'Code':list('abscscbcdbcsscae'),
    'Value':[4,5,6,5,6,2,3,4,5,6,4,5,4,3,6,5]
}

# Creating a DataFrame
df = pd.DataFrame(d)

# Display original DataFrame
print("Original DataFrame:\n",df,"\n")

# Getting groupby sorted result
res = df[['Code','Value']].groupby(['Code'])['Value'].count().reset_index(name='count').sort_values(['count'], ascending=True)

# Display Result
print("Result:\n",res)

Output

The output of the above program is:

Example: Count and Sort with Pandas

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.