- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
Advertisements