Groupby mean in pandas dataframe python

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

  • Groupby single column in pandas – groupby mean
  • Groupby multiple columns in pandas – groupby mean

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 mean in pandas dataframe python 1

 

Groupby single column – groupby mean pandas python:


''' Groupby single column in pandas python'''
df1.groupby(['State'])['Sales'].mean()

We will groupby mean with single column (State), so the result will be

Group by mean in pandas dataframe python 2

 

Groupby multiple columns – groupby mean pandas python:


''' Groupby multiple columns in pandas python'''
df1.groupby(['State','Name'])['Sales'].mean()

We will groupby mean with State and Name columns, so the result will be

Group by mean in pandas dataframe python 3

 

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