Skip to content

Informatics Practices · Ch 3 — Data Handling using Pandas – II

GROUP BY Functions

3.5

GROUP BY Functions

The groupby() function in Pandas is used to split a DataFrame into groups based on some criterion — typically the values in one or more columns. This is not just a way to rearrange data; it is the foundation for performing separate calculations on each group.

The function works on a split-apply-combine strategy, which happens in three clear steps:

  1. Split the original DataFrame into groups by creating a GroupBy object.
  2. Apply the required function (like sum, mean, or a custom function) to each group independently.
  3. Combine the results into a new DataFrame or Series.

To see this in action, imagine a simple two-column DataFrame: one column called key (with values A, B, C) and another called data. If you want the sum of data for each key, you first split the rows into three groups (all A rows together, all B rows together, all C rows together). Then you apply the sum function to each group. Finally, you combine the three sums into a new DataFrame showing A: 15, B: 30, C: 45 (as in the textbook's Figure 3.1).


Creating a GroupBy Object

You create a GroupBy object by calling df.groupby('column_name'). This does not compute anything yet — it just stores the grouping information.

g1 = df.groupby('Name')

Once you have this object, you can inspect the groups in several ways:

  • g1.first() — displays the first row from each group. For the textbook's DataFrame df, this shows each student's first UT scores.
  • g1.size() — returns the number of rows in each group. All four students (Ashravy, Mishti, Raman, Zuhaire) have 3 rows each.
  • g1.groups — a dictionary where keys are group names and values are the row indices belonging to that group. For example, 'Ashravy': Int64Index([6, 7, 8], dtype='int64') means rows 6, 7, and 8 belong to Ashravy.
  • g1.get_group('Raman') — extracts the entire DataFrame for a single group. This returns all rows where Name is 'Raman'.

Grouping by Multiple Columns

You can group by more than one column by passing a list of column names:

g2 = df.groupby(['Name', 'UT'])

This creates groups for each unique combination of student and unit test. Calling g2.first() shows the first occurrence of each combination — effectively a multi-indexed view of the data.


Aggregation: Applying Functions to Groups

Once groups are created, the next step is to apply functions. This is called aggregation — it returns a single aggregated value (like mean, sum, or standard deviation) for each group.

Aggregation is done using the agg() or aggregate() function. By default, functions are applied column-wise.

Example 1: Average marks scored by all students in each subject for each UT.

df.groupby(['UT']).aggregate('mean')

This produces a table with UT numbers as rows and subjects as columns, each cell containing the average marks for that UT.

Example 2: Average marks in Maths for each UT.

group1 = df.groupby(['UT'])
group1['Maths'].aggregate('mean')

Here, you first create the GroupBy object, then select only the Maths column before applying the mean. The result is a Series with UT numbers as the index.


Applying Multiple Aggregate Functions

You can apply several different functions at once by passing a list of function names to agg().

Program 3-10 from the textbook demonstrates this: to print the mean, variance, standard deviation, and quartile of Maths marks for each student across all UTs.

df.groupby(by='Name')['Maths'].agg(['mean', 'var', 'std', 'quantile'])

The output is a DataFrame where each row is a student and each column is one of the requested statistics. For example, Ashravy has a mean of 19.67, variance 44.33, standard deviation 6.66, and quartile 23.0. …

Figure 3.1A DataFrame with two columns
Fig. 3.1 — A DataFrame with two columns

Drawn by us to help you understand the concept clearly, and verified to make sure it's accurate. For exams, practice from your textbook's own diagram.

The figure is a schematic that walks through the three steps of the split-apply-combine strategy for a GROUP BY operation. It uses a simple two-column DataFrame as a concrete example.

On the far left, you see the original DataFrame. It has two columns labelled 'key' and 'data'. There are nine rows. The 'key' column contains the values A, B, and C repeated in that order three times: A, B, C, A, B, C, A, B, C. The corresponding 'data' column holds the numbers 0, 5, 10, 5, 10, 15, 10, 15, 20. So the pairs are (A,0), (B,5), (C,10), (A,5), (B,10), (C,15), (A,10), (B,15), (C,20).

An arrow labelled 'split' points from this DataFrame to the middle section. The split step separates the nine rows into three distinct groups based on the 'key' column. Each group is shown as its own mini-DataFrame. Group A contains the three rows where key is A, with data values 0, 5, and 10. Group B contains the rows with key B, data values 5, 10, and 15. Group C contains the rows with key C, data values 10, 15, and 20.

Next, an arrow labelled 'Apply' leads from each group to a box that says 'Sum'. This is the apply step: the sum function is applied to the 'data' column within each group. For group A, the sum is 0+5+10 = 15. For group B, it is 5+10+15 = 30. For group C, it is 10+15+20 = 45.

Finally, an arrow labelled 'Combine' takes those three results and assembles them into a new, smaller DataFrame on the far right. This result DataFrame has two columns again: 'key' and 'data'. It has three rows: A with data 15, B with data 30, and C with data 45. …

Table 3.27Output of g1.first() -- first row of each Name group
NameUTMathsScienceS.StHindiEng
Ashravy12319201522
Mishti11522252222
Raman12221182021
Table 3.28Output of g1.size() -- number of rows in each Name group
NameSize
Ashravy3
Mishti3
Raman3
Table 3.29Output of g1.get_group('Raman')
IndexUTMathsScienceS.StHindiEng
012221182021
122120172224
Table 3.30Output of g2.first() -- grouped by Name and UT
NameUTMathsScienceS.StHindiEng
Ashravy12319201522
Ashravy22422241721
Ashravy31225192123
Mishti11522252222
Mishti21821252423
Mishti31718202520
Raman12221182021
Raman22120172224
Raman31419152423
Zuhaire12017222419
Zuhaire22315212515
Table 3.31Output of df.GROUP BY(['UT']).aggregate('mean')
UTMathsScienceS.StHindiEng
120.0019.7521.2520.2521.00
221.5019.5021.7522.0020.75
Table 3.32Output of group1['Maths'].aggregate('mean') -- average Maths marks per UT
UTMean Maths
120.00
221.50
316.25
DefinitionProgram 3-10

Write the python statements to print the mean, variance, standard deviation and quartile of the marks scored in Mathematics by each student across the UTs. This chains GROUP BY() with agg() to compute four differe …