Home >Backend Development >Python Tutorial >How to Sum Values within Groups Using Pandas GroupBy?

How to Sum Values within Groups Using Pandas GroupBy?

Barbara Streisand
Barbara StreisandOriginal
2024-12-20 03:56:13362browse

How to Sum Values within Groups Using Pandas GroupBy?

How to Calculate Summation Using Pandas GroupBy

In data science, it is often necessary to aggregate data to gain insights. One common aggregation technique is summing values within groups. The Python library Pandas provides the versatile GroupBy function to group data and perform various operations, including summation.

Consider the following DataFrame:

Fruit Date Name Number
Apples 10/6/2016 Bob 7
Apples 10/6/2016 Bob 8
Apples 10/6/2016 Mike 9
Apples 10/7/2016 Steve 10
Apples 10/7/2016 Bob 1
Oranges 10/7/2016 Bob 2
Oranges 10/6/2016 Tom 15
Oranges 10/6/2016 Mike 57
Oranges 10/6/2016 Bob 65
Oranges 10/7/2016 Tony 1
Grapes 10/7/2016 Bob 1
Grapes 10/7/2016 Tom 87
Grapes 10/7/2016 Bob 22
Grapes 10/7/2016 Bob 12
Grapes 10/7/2016 Tony 15

To obtain the total number of Fruits purchased by each Name, use the GroupBy.sum() method:

df.groupby(['Name', 'Fruit']).sum()

This will produce the following output:

Fruit Name Number
Apples Bob 16
Apples Mike 9
Apples Steve 10
Grapes Bob 35
Grapes Tom 87
Grapes Tony 15
Oranges Bob 67
Oranges Mike 57
Oranges Tom 15
Oranges Tony 1

The above is the detailed content of How to Sum Values within Groups Using Pandas GroupBy?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn