Bird
Raised Fist0
Data Analysis Pythondata~20 mins

Cross-tabulation with crosstab() in Data Analysis Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Cross-tabulation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ data_output
intermediate
2:00remaining
Output of simple crosstab() with two categorical columns
Given the DataFrame below, what is the output of the crosstab() function?
Data Analysis Python
import pandas as pd

data = {'Gender': ['Male', 'Female', 'Female', 'Male', 'Female'],
        'Preference': ['Coffee', 'Coffee', 'Tea', 'Coffee', 'Tea']}
df = pd.DataFrame(data)

result = pd.crosstab(df['Gender'], df['Preference'])
print(result)
A
Preference  Coffee  Tea
Gender                 
Female          1    2
Male            2    0
B
Preference  Coffee  Tea
Gender                 
Female          2    1
Male            1    2
C
Preference  Coffee  Tea
Gender                 
Female          1    3
Male            2    0
D
Preference  Coffee  Tea
Gender                 
Female          0    2
Male            2    1
Attempts:
2 left
💡 Hint
Count how many times each Gender prefers Coffee or Tea.
🧠 Conceptual
intermediate
1:30remaining
Understanding margins parameter in crosstab()
What does setting the parameter margins=true do in the pd.crosstab() function?
ANormalizes the crosstab values to show proportions instead of counts.
BAdds a row and column with totals (sum) for each category and overall.
CFilters the crosstab to only show rows with more than 5 counts.
DSorts the crosstab rows and columns alphabetically.
Attempts:
2 left
💡 Hint
Think about what 'margins' means in tables.
🔧 Debug
advanced
2:00remaining
Identify the error in crosstab() usage
What error will this code raise?
Data Analysis Python
import pandas as pd

ages = [23, 45, 31, 35]
genders = ['M', 'F', 'F', 'M']

# Valid: passing lists to crosstab
result = pd.crosstab(ages, genders, margins=True)
print(result)
ANo error, prints the crosstab table
BTypeError: unhashable type: 'list'
CTypeError: Cannot interpret 'ages' as a data frame column
DValueError: Index contains duplicate entries, cannot reshape
Attempts:
2 left
💡 Hint
pd.crosstab accepts lists as array-like inputs.
❓ visualization
advanced
2:30remaining
Visualizing crosstab output with a heatmap
Which code snippet correctly creates a heatmap visualization of the crosstab result using seaborn?
Data Analysis Python
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

data = {'City': ['NY', 'LA', 'NY', 'LA', 'NY'],
        'Transport': ['Car', 'Bus', 'Bus', 'Car', 'Car']}
df = pd.DataFrame(data)

ct = pd.crosstab(df['City'], df['Transport'])
A
plt.plot(ct)
plt.show()
B
sns.barplot(data=ct)
plt.show()
C
sns.heatmap(ct, annot=True)
plt.show()
D
sns.scatterplot(data=ct)
plt.show()
Attempts:
2 left
💡 Hint
Heatmaps are good for showing tables with numbers.
🚀 Application
expert
3:00remaining
Using crosstab() to analyze survey data with normalization
You have a DataFrame with columns 'AgeGroup' and 'Satisfaction' from a survey. You want to see the proportion of each satisfaction level within each age group (rows sum to 1). Which crosstab() call achieves this?
Data Analysis Python
import pandas as pd

data = {'AgeGroup': ['18-25', '18-25', '26-35', '26-35', '26-35', '36-45'],
        'Satisfaction': ['High', 'Low', 'Medium', 'High', 'Low', 'High']}
df = pd.DataFrame(data)
Apd.crosstab(df['AgeGroup'], df['Satisfaction'], margins=True, normalize='all')
Bpd.crosstab(df['AgeGroup'], df['Satisfaction'], normalize='columns')
Cpd.crosstab(df['AgeGroup'], df['Satisfaction'], normalize=True)
Dpd.crosstab(df['AgeGroup'], df['Satisfaction'], normalize='index')
Attempts:
2 left
💡 Hint
Normalization by 'index' means row-wise proportions.

Practice

(1/5)
1. What does the pd.crosstab() function do in data analysis?
easy
A. It sorts data in ascending order.
B. It counts how often categories from two variables appear together.
C. It calculates the average of numerical columns.
D. It removes missing values from the dataset.

Solution

  1. Step 1: Understand the purpose of crosstab()

    The function pd.crosstab() is used to count occurrences of combinations of categories from two variables.
  2. Step 2: Compare with other options

    Sorting, averaging, and removing missing values are different functions, not related to crosstab.
  3. Final Answer:

    It counts how often categories from two variables appear together. -> Option B
  4. Quick Check:

    Cross-tabulation = counts of category pairs [OK]
Hint: Remember: crosstab counts category pairs, not calculations [OK]
Common Mistakes:
  • Thinking crosstab sorts data
  • Confusing crosstab with aggregation functions
  • Assuming crosstab cleans data
2. Which of the following is the correct syntax to create a cross-tabulation table using pandas?
easy
A. pd.crosstab(index=df['AgeGroup'], columns=df['Gender'])
B. pd.crosstab(df.Gender, columns='AgeGroup')
C. pd.crosstab(columns=df['Gender'], index=df['AgeGroup'])
D. pd.crosstab(df['Gender'], df['AgeGroup'])

Solution

  1. Step 1: Recall the correct parameter order for crosstab()

    The function pd.crosstab() takes the first argument as the row variable and the second as the column variable, both as Series or arrays.
  2. Step 2: Check each option

    pd.crosstab(df['Gender'], df['AgeGroup']) correctly passes two Series without naming parameters. pd.crosstab(index=df['AgeGroup'], columns=df['Gender']) uses named parameters with row and column variables reversed. pd.crosstab(df.Gender, columns='AgeGroup') passes a string literal instead of a Series for the columns parameter. pd.crosstab(columns=df['Gender'], index=df['AgeGroup']) swaps index and columns incorrectly.
  3. Final Answer:

    pd.crosstab(df['Gender'], df['AgeGroup']) -> Option D
  4. Quick Check:

    Use positional args: rows, columns [OK]
Hint: Use positional args: first is rows, second is columns [OK]
Common Mistakes:
  • Swapping index and columns parameters
  • Mixing positional and named arguments incorrectly
  • Passing DataFrame instead of Series
3. Given the DataFrame:
import pandas as pd
data = {'Color': ['Red', 'Blue', 'Red', 'Green', 'Blue', 'Green'],
        'Shape': ['Circle', 'Square', 'Square', 'Circle', 'Circle', 'Square']}
df = pd.DataFrame(data)
print(pd.crosstab(df['Color'], df['Shape']))

What is the output?
medium
A. Shape Circle Square Color Blue 1 1 Green 1 1 Red 1 1
B. Shape Circle Square Color Blue 2 0 Green 0 2 Red 1 1
C. Shape Circle Square Color Blue 1 0 Green 1 1 Red 1 1
D. Shape Circle Square Color Blue 1 1 Green 1 0 Red 1 1

Solution

  1. Step 1: Count occurrences of each Color-Shape pair

    From the data:
    - Blue: Circle(1), Square(1)
    - Green: Circle(1), Square(1)
    - Red: Circle(1), Square(1)
  2. Step 2: Construct the crosstab table

    Each color has one Circle and one Square, so the table shows 1 for each pair.
  3. Final Answer:

    Shape Circle Square Color Blue 1 1 Green 1 1 Red 1 1 -> Option A
  4. Quick Check:

    Count pairs correctly = Shape Circle Square Color Blue 1 1 Green 1 1 Red 1 1 [OK]
Hint: Count each category pair carefully from data [OK]
Common Mistakes:
  • Miscounting pairs
  • Swapping rows and columns
  • Ignoring repeated categories
4. What is wrong with this code snippet?
import pandas as pd
data = {'Team': ['A', 'B', 'A', 'B'], 'Result': ['Win', 'Lose', 'Lose', 'Win']}
df = pd.DataFrame(data)
ct = pd.crosstab(index=df['Team'], columns='Result')
print(ct)
medium
A. The DataFrame is missing a column named 'Result'.
B. The index parameter should be a list, not a Series.
C. The columns parameter should be a Series, not a string.
D. The crosstab function requires numeric data only.

Solution

  1. Step 1: Check the columns argument in crosstab()

    The columns argument must be a Series or array representing categories, not a string literal.
  2. Step 2: Identify the error in the code

    Here, columns='Result' is a string, not df['Result']. This causes crosstab to treat it incorrectly.
  3. Final Answer:

    The columns parameter should be a Series, not a string. -> Option C
  4. Quick Check:

    Columns must be Series, not string [OK]
Hint: Pass Series for index and columns, not strings [OK]
Common Mistakes:
  • Passing column name as string instead of Series
  • Assuming crosstab needs numeric data
  • Confusing index and columns parameters
5. You have a DataFrame with columns 'Department' and 'Satisfaction' (values: 'High', 'Medium', 'Low'). You want to find how many employees in each department have each satisfaction level, but only show departments with at least 3 employees total. Which code correctly does this?
hard
A. ct = pd.crosstab(df['Department'], df['Satisfaction']) ct = ct[ct.sum(axis=1) >= 3]
B. ct = pd.crosstab(index=df['Satisfaction'], columns=df['Department']) ct = ct[ct.sum(axis=0) >= 3]
C. ct = pd.crosstab(df['Department'], df['Satisfaction']) ct = ct[ct.sum(axis=0) >= 3]
D. ct = pd.crosstab(index=df['Department'], columns=df['Satisfaction']) ct = ct[ct.sum(axis=1) < 3]

Solution

  1. Step 1: Create crosstab with Department as rows and Satisfaction as columns

    Use pd.crosstab(df['Department'], df['Satisfaction']) to count satisfaction levels per department.
  2. Step 2: Filter departments with total employees >= 3

    Sum counts across columns (axis=1) for each department, then keep rows where sum >= 3.
  3. Final Answer:

    ct = pd.crosstab(df['Department'], df['Satisfaction']) ct = ct[ct.sum(axis=1) >= 3] -> Option A
  4. Quick Check:

    Filter rows by sum(axis=1) >= 3 [OK]
Hint: Sum rows (axis=1) to filter departments by total count [OK]
Common Mistakes:
  • Filtering columns instead of rows
  • Swapping index and columns in crosstab
  • Using wrong axis in sum()
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard