Cross tab in python pandas (cross table)

In this tutorial we will learn how to create cross tab in python pandas  ( 2 way cross table or  3 way cross table or contingency table) with example. We will learn how to create.

  • 2 way cross table or contingency table in python pandas
  • 3 way cross table or contingency table in python pandas

 

Create dataframe :

import pandas as pd
import numpy as np

#Create a DataFrame
d = {
    'Name':['Alisa','Bobby','Cathrine','Alisa','Bobby','Cathrine',
            'Alisa','Bobby','Cathrine','Alisa','Bobby','Cathrine'],
    'Exam':['Semester 1','Semester 1','Semester 1','Semester 1','Semester 1','Semester 1',
            'Semester 2','Semester 2','Semester 2','Semester 2','Semester 2','Semester 2'],
    
    'Subject':['Mathematics','Mathematics','Mathematics','Science','Science','Science',
               'Mathematics','Mathematics','Mathematics','Science','Science','Science'],
   'Result':['Pass','Pass','Fail','Pass','Fail','Pass','Pass','Fail','Fail','Pass','Pass','Fail']}

df = pd.DataFrame(d,columns=['Name','Exam','Subject','Result'])
df

so the resultant dataframe will be

2 way 3 way Cross tab (cross table) in python pandas 1

 

2 Way Cross table in python pandas:

We will calculate the cross table of subject and result as shown below


# 2 way cross table

pd.crosstab(df.Subject, df.Result,margins=True)

margin=True displays the row wise and column wise sum of the cross table  so the output will be

2 way 3 way Cross tab (cross table) in python pandas 2

 

3 Way Cross table in python pandas:

We will calculate the cross table of subject, Exam and result as shown below


# 3 way cross table

pd.crosstab([df.Subject, df.Exam],df.Result, margins=True)

the result will be

2 way 3 way Cross tab (cross table) in python pandas 3

 

previous-small Cross tab in python pandas (cross table)                                                                                                                next_small Cross tab in python pandas (cross table)