Group by sum in pandas dataframe python

Group by sum in pandas python can be accomplished by groupby() function. let’s  see how to

  • Group by single column in pandas
  • Group by multiple columns in pandas

First let’s create a dataframe

import pandas as pd
import numpy as np

data = {'Name':['James','Paul','Richards','Marico','Samantha','Ravi','Raghu','Richards','George','Ema','Samantha','Catherine'],
       'State':['Alaska','California','Texas','North Carolina','California','Texas','Alaska','Texas','North Carolina','Alaska','California','Texas'],
       'Sales':[14,24,31,12,13,7,9,31,18,16,18,14]}

df1=pd.DataFrame(data, columns=['Name','State','Sales'])

print(df1)

df1 will be

Group by sum in pandas dataframe python 1

 

Group by single column – group by sum pandas python:


''' Group by single column in pandas python'''
df1.groupby(['State'])['Sales'].sum()

We will group by sum with single column (State), so the result will be

Group by sum in pandas dataframe python 2

 

Group by multiple columns – group by sum pandas python:


''' Group by multiple columns in pandas python'''
df1.groupby(['State','Name'])['Sales'].sum()

We will group by sum with State and Name columns, so the result will be

Group by sum in pandas dataframe python 3

p Group by sum in pandas dataframe python                                                                                                               n Group by sum in pandas dataframe python