Python for Data Science: Chapter 5: NumPy and Pandas Libraries

Pandas: Grouping

Python library

Grouping involves creating subsets of data based on one or more columns. This is useful when you want to analyze and compare data within specific categories.

Grouping

•  Grouping involves creating subsets of data based on one or more columns. This is useful when you want to analyze and compare data within specific categories.

•  There are three important activities that take place during grouping operation ‒

1) Splitting data into groups based on some criteria.

2) Applying a function to each group independently.

3) Combining the result into a data structure.

•  For example ‒ Consider following data set



Demo example

We will consider the data set for health expenses spent by each country in the year 1970,1971, 1972. Also this data set shows the life expectancy according to the country. The code to read this data set is as follows ‒

import pandas as pd

spendings =

pd.DataFrame({'Year: [1970, 1970, 1970, 1970, 1970, 1971, 1971, 1971, 1971, 1971,1972,1972, 1972],

 'Country': ['Germany', 'France', 'Great_Britain', 'Japan', 'USA','Canada',

'Germany', 'Great_Britain', 'Japan', 'USA', 'Germany', 'Japan', 'USA'],

'Spending USD': [252,192,123,150,326,313,298,134,163,357,337,185,397],

 'Life Expectancy': [70,72,71,72,71,73,70,72,73,71,71,74,71]},

columns = ['Year', 'Country','Spending_USD','Life Expectancy'])

spendings

Output


 

Python for Data Science: Chapter 5: NumPy and Pandas Libraries : Tag: Computer Programming, Python, Data Science : Python library - Pandas: Grouping


Python for Data Science: Chapter 5: NumPy and Pandas Libraries



Under Subject


Python for Data Science

AD25201 2nd Semester AIDS Dept | 2025 Regulation | 2nd Semester 2025 Regulation



Related Subjects


English Essentials II

EN25C02 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation



Linear Algebra

MA25C02 2nd Semester | 2025 Regulation


Applied Physics (CSIE) II

PH25C03 2nd Semester AIDS, CSE, IT, CSE(CY) Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Digital Principles and Computer Organization

CS25C06 2nd Semester AIDS, CSE, IT, CSE(CY) Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Basic Electrical and Electronics Engineering

EE25C01 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation


Python for Data Science

AD25201 2nd Semester AIDS Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Re-Engineering for Innovation

ME25C05 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation


Python for Data Science - Laboratory

AD25201 2nd Semester AIDS Dept | 2025 Regulation | 2nd Semester 2025 Regulation