![]() |
VOOZH | about |
When working with large datasets it's used to group and summarize the data to make analysis easier. Pandas a popular Python library provides powerful tools for this. In this article you'll learn how to use Pandas' groupby() and aggregation functions step by step with clear explanations and practical examples.
Aggregation means applying a mathematical function to summarize data. It can be used to get a summary of columns in our dataset like getting sum, minimum, maximum etc. from a particular column of our dataset. The function used for aggregation is agg() the parameter is the function we want to perform. Some functions used in the aggregation are:
| Function | Description |
|---|---|
| sum() | Compute sum of column values |
| min() | Compute min of column values |
| max() | Compute max of column values |
| mean() | Compute mean of column |
| size() | Compute column sizes |
| describe() | Generates descriptive statistics |
| first() | Compute first of group values |
| last() | Compute last of group values |
| count() | Compute count of column values |
| std() | Standard deviation of column |
| var() | Compute variance of column |
| sem() | Standard error of the mean of column |
Let's create a small dataset of student marks in Maths, English, Science and History.
Output:
๐ ImageNow that we have a dataset letโs perform aggregation.
The sum() function adds up all values in each column.
Output:
๐ ImageInstead of calculating sum, mean, min and max separately we can use describe() which provides all important statistics in one go.
Output:
๐ ImageThe .agg() function lets you apply multiple aggregation functions at the same time.
Output:
๐ ImageGrouping in Pandas means organizing your data into groups based on some columns. Once grouped you can perform actions like finding the total, average, count or even pick the first row from each group. This method follows a split-apply-combine process:
Letโs understand grouping in Pandas using a small bakery order dataset as an example.
Output:
Letโs say we want to group the orders based on the Item column.
Output:
<pandas.core.groupby.generic.DataFrameGroupBy object at 0x7867484be150>
This doesn't show the result directly it just creates a grouped object. To actually see the data we need to apply a method like .sum(), .mean() or first(). Letโs find the total price of each item sold:
Output:
The above output shows the total earnings from each item.
Now letโs group by Item and Flavor to see how each flavored item sold.
Output:
The above output show Chocolate Cakes earned โน500 and Vanilla Cake earned โน220 and more.