Grouping Basics

Lesson Introduction

Welcome to the lesson on "Grouping Basics" in Pandas! Today, we will learn why grouping is important in data analysis and how to use it to find meaningful insights.

Why use grouping in data analysis?
Imagine you run a lemonade stand and want to see which flavors sell the most. Grouping sales by each flavor helps you see the total amount sold for each one. This helps answer questions like which products are popular and who the best salesperson is.

By the end of this lesson, you'll know how to group data in Pandas and apply simple functions to these groups. We'll use real-life examples to make the concepts clearer and easier to understand.

Grouping Data

Grouping data means organizing it by common values in one or more columns. If you've sorted your toys by type — like cars in one bin and dolls in another — you're familiar with grouping.

Grouping is useful when summarizing or analyzing subsets of data. For instance, if you're managing a sales team, you might want to see the total sales for each representative to find out who is performing best.

Example: Dataset

We'll start with a simple dataset containing information about sales made by different representatives.

Python
# Import pandas library
import pandas as pd

# Create the sales data as a dictionary
data = {
    'Representative': ['Alice', 'Bob', 'Alice', 'Bob', 'Charlie', 'Charlie'],
    'Region': ['East', 'West', 'West', 'East', 'East', 'West'],
    'Sales': [150, 200, 100, 250, 175, 300]
}

# Convert the dictionary to a DataFrame
df = pd.DataFrame(data)
print(df)

Output:

  Representative Region  Sales
0          Alice   East    150
1            Bob   West    200
2          Alice   West    100
3            Bob   East    250
4        Charlie   East    175
5        Charlie   West    300

Example: Using `groupby`

Now, let's introduce the groupby method in Pandas, which groups data by specific values in a column.

Python
# Group the data by 'Representative'
grouped = df.groupby('Representative')

The result of the operation – grouped – is a special object, that contains our data in a proper grouped format. If you print this object, you will see something like <pandas.core.groupby.generic.DataFrameGroupBy object at 0x1169eb820>, because this object doesn't have the __repr__ method. So, instead, let's go see it in action!

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal