Write a Python code to find a cross tabulation of two dataframes


Assume you have two dataframes and the result for cross-tabulation is,

Age  12 13 14
Mark 80 90 85
Id
1    1  0  0
2    0  1  0
3    1  0  0
4    0  1  0
5    0  0  1

Solution

To solve this, we will follow the steps given below −

  • Define two dataframes

  • Apply df.crosstab() function inside index as ‘Id’ and columns as ‘Age’ and ‘Mark’. It is defined below,

pd.crosstab(index=df['Id'],columns=[df['Age'],df1['Mark']])

Example

import pandas as pd
df = pd.DataFrame({'Id':[1,2,3,4,5],'Age':[12,13,12,13,14]})
df1 = pd.DataFrame({'Mark':[80,90,80,90,85]})
print(pd.crosstab(index=df['Id'],columns=[df['Age'],df1['Mark']]))

Output

Age  12 13 14
Mark 80 90 85
Id
1    1  0  0
2    0  1  0
3    1  0  0
4    0  1  0
5    0  0  1

Updated on: 25-Feb-2021

438 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements