Bird
Raised Fist0
Pandasdata~20 mins

crosstab() for cross-tabulation in Pandas - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Crosstab Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ data_output
intermediate
2:00remaining
Output of simple crosstab() usage

What is the output of the following code?

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)
Pandas
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     1
C
Preference  Coffee  Tea
Gender                 
Female          1     2
Male            1     0
D
Preference  Coffee  Tea
Gender                 
Female          1     1
Male            2     1
Attempts:
2 left
💡 Hint

Count how many times each gender prefers each drink.

🧠 Conceptual
intermediate
1:30remaining
Understanding margins in crosstab()

What does the margins=True parameter add to the output of pd.crosstab()?

AIt filters the data to only include rows with missing values.
BIt adds a row and column showing the total counts for each category.
CIt normalizes the counts to show proportions instead of raw counts.
DIt sorts the rows and columns alphabetically.
Attempts:
2 left
💡 Hint

Think about what 'margins' means in a table context.

❓ Predict Output
advanced
2:30remaining
Output with multiple aggregation functions

What is the output of this code?

import pandas as pd

data = {'Team': ['A', 'A', 'B', 'B', 'A'],
        'Result': ['Win', 'Lose', 'Win', 'Lose', 'Win'],
        'Points': [3, 0, 3, 0, 3]}
df = pd.DataFrame(data)

result = pd.crosstab(df['Team'], df['Result'], values=df['Points'], aggfunc='sum', margins=True)
print(result)
Pandas
import pandas as pd

data = {'Team': ['A', 'A', 'B', 'B', 'A'],
        'Result': ['Win', 'Lose', 'Win', 'Lose', 'Win'],
        'Points': [3, 0, 3, 0, 3]}
df = pd.DataFrame(data)

result = pd.crosstab(df['Team'], df['Result'], values=df['Points'], aggfunc='sum', margins=True)
print(result)
A
Result  Lose  Win  All
Team                   
A          0    3    3
B          0    3    3
All        0    6    6
B
Result  Lose  Win  All
Team                   
A          0    9    9
B          0    3    3
All        0   12   12
C
Result  Lose  Win  All
Team                   
A          0    6    9
B          0    3    3
All        0    9   12
D
Result  Lose  Win  All
Team                   
A          0    6    6
B          0    3    3
All        0    9    9
Attempts:
2 left
💡 Hint

Sum points for each team and result, then add totals.

🔧 Debug
advanced
2:00remaining
Identify the error in crosstab() usage

What error will this code produce?

import pandas as pd

data = {'Category': ['X', 'Y', 'X'], 'Value': [10, 20, 30]}
df = pd.DataFrame(data)

result = pd.crosstab(df['Category'], df['Value'], aggfunc='sum')
print(result)
Pandas
import pandas as pd

data = {'Category': ['X', 'Y', 'X'], 'Value': [10, 20, 30]}
df = pd.DataFrame(data)

result = pd.crosstab(df['Category'], df['Value'], aggfunc='sum')
print(result)
ATypeError: Cannot specify 'aggfunc' without 'values' parameter
BNo error, outputs a frequency table
CValueError: aggfunc must be a string, function or list of functions
DKeyError: 'Value' column not found
Attempts:
2 left
💡 Hint

Check if 'values' parameter is provided when using 'aggfunc'.

🚀 Application
expert
2:30remaining
Using crosstab() to analyze survey data

You have survey data with columns AgeGroup and FavoriteFruit. You want to find the percentage distribution of favorite fruits within each age group. Which code snippet produces this result?

Apd.crosstab(df['AgeGroup'], df['FavoriteFruit'], normalize=True)
Bpd.crosstab(df['AgeGroup'], df['FavoriteFruit'], normalize='columns')
Cpd.crosstab(df['AgeGroup'], df['FavoriteFruit'], normalize='index')
Dpd.crosstab(df['AgeGroup'], df['FavoriteFruit'], margins=True)
Attempts:
2 left
💡 Hint

Think about normalizing rows to get percentages within each age group.

Practice

(1/5)
1. What does the pandas.crosstab() function primarily do?
easy
A. Filters rows based on a condition
B. Sorts data in ascending order
C. Counts how often values from two columns appear together
D. Calculates the mean of numerical columns

Solution

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

    The crosstab() function creates a table showing frequency counts of combinations of values from two or more columns.
  2. Step 2: Compare with other options

    Sorting, calculating mean, and filtering are different operations not done by crosstab().
  3. Final Answer:

    Counts how often values from two columns appear together -> Option C
  4. Quick Check:

    crosstab() = frequency count [OK]
Hint: Remember: crosstab counts pairs of values [OK]
Common Mistakes:
  • Confusing crosstab with sorting or filtering
  • Thinking crosstab calculates averages
  • Assuming crosstab modifies original data
2. Which of the following is the correct syntax to create a crosstab of columns 'A' and 'B' from DataFrame df?
easy
A. pd.crosstab(df.A, df.B, axis=1)
B. pd.crosstab(df['A'], df['B'])
C. df.crosstab('A', 'B')
D. pd.crosstab(df['A', 'B'])

Solution

  1. Step 1: Recall correct crosstab syntax

    The correct syntax is pd.crosstab(df['A'], df['B']) where you pass two series as arguments.
  2. Step 2: Identify incorrect options

    pd.crosstab(df.A, df.B, axis=1) wrongly uses axis parameter; df.crosstab('A', 'B') tries to call crosstab as a DataFrame method which doesn't exist; pd.crosstab(df['A', 'B']) passes a tuple incorrectly.
  3. Final Answer:

    pd.crosstab(df['A'], df['B']) -> Option B
  4. Quick Check:

    pd.crosstab(series1, series2) = correct syntax [OK]
Hint: Use pd.crosstab(series1, series2) syntax [OK]
Common Mistakes:
  • Calling crosstab as a DataFrame method
  • Passing multiple columns as a tuple incorrectly
  • Using wrong parameters like axis
3. Given the DataFrame:
import pandas as pd
data = {'Gender': ['M', 'F', 'F', 'M', 'F'], 'Preference': ['Tea', 'Coffee', 'Tea', 'Coffee', 'Tea']}
df = pd.DataFrame(data)

What is the output of pd.crosstab(df['Gender'], df['Preference'])?
medium
A. Preference Coffee Tea Gender F 1 2 M 1 1
B. Preference Coffee Tea Gender F 2 1 M 1 1
C. Preference Coffee Tea Gender F 1 1 M 2 1
D. Preference Coffee Tea Gender F 1 2 M 2 0

Solution

  1. Step 1: Count occurrences for each Gender and Preference

    For 'F': Coffee appears once, Tea appears twice. For 'M': Coffee appears once, Tea appears once.
  2. Step 2: Construct the crosstab table

    Rows are Gender (F, M), columns are Preference (Coffee, Tea), with counts filled accordingly.
  3. Final Answer:

    Preference Coffee Tea Gender F 1 2 M 1 1 -> Option A
  4. Quick Check:

    Count values by groups = Preference Coffee Tea Gender F 1 2 M 1 1 [OK]
Hint: Count each group pair carefully for crosstab [OK]
Common Mistakes:
  • Mixing up row and column labels
  • Counting values incorrectly
  • Assuming missing pairs have counts > 0
4. What is wrong with this code snippet?
import pandas as pd
data = {'A': ['x', 'y', 'x'], 'B': ['p', 'q', 'p']}
df = pd.DataFrame(data)
result = pd.crosstab(df['A'], df['B'], margins=True, margin_name='Total')
print(result)

It raises an error. Why?
medium
A. The print statement is missing parentheses
B. You cannot use margins=True with crosstab
C. The DataFrame columns must be numeric for crosstab
D. The parameter name should be margins_name, not margin_name

Solution

  1. Step 1: Check parameter names for crosstab()

    The correct parameter to name the totals row/column is margins_name, not margin_name.
  2. Step 2: Identify the cause of error

    Using margin_name causes a TypeError because it's an unexpected keyword argument.
  3. Final Answer:

    The parameter name should be margins_name, not margin_name -> Option D
  4. Quick Check:

    Correct parameter is margins_name [OK]
Hint: Use margins_name, not margin_name for totals [OK]
Common Mistakes:
  • Misspelling parameter names
  • Thinking crosstab requires numeric columns
  • Forgetting parentheses in print (Python 3)
5. You have a DataFrame df with columns 'City', 'Product', and 'Sales'. You want to create a crosstab showing total sales for each city-product pair. Which code correctly achieves this?
hard
A. pd.crosstab(df['City'], df['Product'], values=df['Sales'], aggfunc='sum')
B. pd.crosstab(df['City'], df['Product'], values='Sales', aggfunc='sum')
C. pd.crosstab(df['City'], df['Product'], aggfunc='sum')
D. pd.crosstab(df['City'], df['Product'], values=df['Sales'])

Solution

  1. Step 1: Understand crosstab with aggregation

    To aggregate values like sales, use values= with the column and aggfunc= with the aggregation function.
  2. Step 2: Check each option

    pd.crosstab(df['City'], df['Product'], values=df['Sales'], aggfunc='sum') correctly passes the sales column and sum function. pd.crosstab(df['City'], df['Product'], values='Sales', aggfunc='sum') passes a string instead of a series for values. pd.crosstab(df['City'], df['Product'], aggfunc='sum') misses values parameter. pd.crosstab(df['City'], df['Product'], values=df['Sales']) misses aggfunc, so it defaults to count.
  3. Final Answer:

    pd.crosstab(df['City'], df['Product'], values=df['Sales'], aggfunc='sum') -> Option A
  4. Quick Check:

    Use values= and aggfunc= for aggregation [OK]
Hint: Use values=column and aggfunc='sum' for totals [OK]
Common Mistakes:
  • Passing column name as string instead of series
  • Omitting aggfunc for aggregation
  • Expecting crosstab to sum without values parameter
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