- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Group-by and Sum in Python Pandas
To find group-by and sum in Python Pandas, we can use groupby(columns).sum().
Steps
- Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
- Print the input DataFrame, df.
- Find the groupby sum using df.groupby().sum(). This function takes a given column and sorts its values. After that, based on the sorted values, it also sorts the values of other columns.
- Print the groupby sum.
Example
import pandas as pd df = pd.DataFrame( { "Apple": [5, 2, 7, 0], "Banana": [4, 7, 5, 1], "Carrot": [9, 3, 5, 1] } ) print "Input DataFrame 1 is:\n", df g_sum = df.groupby(['Apple']).sum() print "Group by Apple is:\n", g_sum
Output
Input DataFrame 1 is: Apple Banana Carrot 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1 Group by Apple is: Apple Banana Carrot 0 1 1 2 7 3 5 4 9 7 5 5
- Related Articles
- Python - How to Group Pandas DataFrame by Minutes?
- Python - How to Group Pandas DataFrame by Year?
- Python - How to Group Pandas DataFrame by Month?
- Python - How to Group Pandas DataFrame by Days?
- Python – Sort grouped Pandas dataframe by group size?
- Python – Group and calculate the sum of column values of a Pandas DataFrame
- Python – Descending Order Sort grouped Pandas dataframe by group size?
- Python – Ascending Order Sort grouped Pandas dataframe by group size?
- Python Pandas - Group the swarms by two categorical variables with Seaborn
- Python Pandas - Group the swarms by a categorical variable with Seaborn
- Python - Sum negative and positive values using GroupBy in Pandas
- Python - Compute last of group values in a Pandas DataFrame
- Python Pandas - Count the number of rows in each group
- Python - How to group DataFrame rows into list in Pandas?
- Python - Compute first of group values in a Pandas DataFrame

Advertisements