Python:Pandas .sum()
Published Jun 11, 2022Updated Apr 20, 2023
Contribute to Docs
The .sum() method produces a new Series or DataFrame with aggregate sums for the groups in a GroupBy object.
Syntax
groupbyobject.sum(numeric_only, min_count)
The .sum() method has the following parameters:
numeric_only: Boolean value.Trueincludes only int, float, and boolean columns. Default value isTrue.min_count: Int value. Required number of valid entries in order to produce a result. Default value is 0.
Example
The following example produces a GroupBy object from a DataFrame and executes the .sum() method on it.
import pandas as pddf = pd.DataFrame({'Key' : ['A', 'A', 'A', 'B', 'B', 'C'],'Value' : [15., 23., 17., 5., 8., 12.]})print(df, end='\n\n')group = df.groupby(['Key'], as_index=False)print(group.sum())
This example produces the following output:
Key Value0 A 15.01 A 23.02 A 17.03 B 5.04 B 8.05 C 12.0Key Value0 A 55.01 B 13.02 C 12.0
Codebyte Example
Use the Codebytes editor below to produce a new Series with the .sum() method.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:Pandas on Codecademy
- Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
- Includes 27 Courses
- With Professional Certification
- Beginner Friendly.95 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours