- 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
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
Advertisements