0
0
Pandasdata~30 mins

crosstab() for cross-tabulation in Pandas - Mini Project: Build & Apply

Choose your learning style9 modes available
Using crosstab() for Cross-Tabulation in pandas
📖 Scenario: You work in a small store and have collected data about customers' gender and whether they bought a product or not. You want to see how many males and females bought or did not buy the product.
🎯 Goal: Build a simple cross-tabulation table using pandas crosstab() to count the number of customers by gender and purchase status.
📋 What You'll Learn
Create a pandas DataFrame with exact customer data
Create a variable for the DataFrame
Use pandas crosstab() with the correct columns
Print the resulting cross-tabulation table
💡 Why This Matters
🌍 Real World
Cross-tabulation helps businesses quickly see relationships between categories, like customer gender and buying behavior.
💼 Career
Data analysts and scientists use crosstab() to summarize and explore categorical data for reports and decision-making.
Progress0 / 4 steps
1
Create the customer data DataFrame
Create a pandas DataFrame called df with two columns: 'Gender' and 'Purchased'. Use these exact values: ['Male', 'Female', 'Female', 'Male', 'Female', 'Male'] for 'Gender' and ['Yes', 'No', 'Yes', 'No', 'Yes', 'Yes'] for 'Purchased'.
Pandas
Need a hint?

Use pd.DataFrame() with a dictionary for columns.

2
Set up the cross-tabulation variable
Create a variable called cross_tab and assign it to the result of pd.crosstab() using df['Gender'] as rows and df['Purchased'] as columns.
Pandas
Need a hint?

Use pd.crosstab() with the two DataFrame columns as arguments.

3
Print the cross-tabulation table
Print the variable cross_tab to display the cross-tabulation table.
Pandas
Need a hint?

Use print(cross_tab) to show the table.

4
Add totals to the cross-tabulation table
Update the cross_tab variable to include row and column totals by adding margins=True inside pd.crosstab(). Then print cross_tab again.
Pandas
Need a hint?

Add margins=True inside pd.crosstab() to get totals.