What is the purpose of the crosstab() function in pandas?
The crosstab() function creates a table that shows the frequency (count) of combinations between two or more categorical variables. It helps to summarize and compare data easily.
Click to reveal answer
beginner
How do you create a simple cross-tabulation between two columns col1 and col2 in a DataFrame df?
Use pd.crosstab(df['col1'], df['col2']). This counts how many times each combination of values from col1 and col2 appears.
Click to reveal answer
intermediate
What does the normalize parameter do in crosstab()?
The normalize parameter changes counts into proportions or percentages. For example, normalize='index' shows row-wise proportions, and normalize='columns' shows column-wise proportions.
Click to reveal answer
intermediate
Can crosstab() handle more than two variables? How?
Yes, by passing multiple arrays or columns as arguments. For example, pd.crosstab([df['col1'], df['col2']], df['col3']) creates a multi-index table showing counts for combinations of col1 and col2 against col3.
Click to reveal answer
beginner
What is a real-life example where crosstab() is useful?
Imagine a survey with answers about gender and favorite fruit. crosstab() can show how many males and females prefer each fruit, helping to understand preferences by group.
Click to reveal answer
What does pd.crosstab(df['A'], df['B']) return?
AA table counting occurrences of each combination of values in columns A and B
BA table showing the sum of values in columns A and B
CA table with the mean of columns A and B
DA table with unique values from columns A and B
✗ Incorrect
crosstab() counts how often each pair of values appears in the two columns.
How do you get proportions instead of counts in crosstab()?
ASet <code>normalize='index'</code> or <code>normalize='columns'</code>
BSet <code>normalize='all'</code>
CSet <code>normalize=True</code>
DSet <code>normalize=False</code>
✗ Incorrect
Use normalize='index' for row proportions or normalize='columns' for column proportions.
Which of these is a valid way to use crosstab() with three variables?
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
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.
Step 2: Construct the crosstab table
Rows are Gender (F, M), columns are Preference (Coffee, Tea), with counts filled accordingly.
Final Answer:
Preference Coffee Tea
Gender
F 1 2
M 1 1 -> Option A
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
Step 1: Check parameter names for crosstab()
The correct parameter to name the totals row/column is margins_name, not margin_name.
Step 2: Identify the cause of error
Using margin_name causes a TypeError because it's an unexpected keyword argument.
Final Answer:
The parameter name should be margins_name, not margin_name -> Option D
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
Step 1: Understand crosstab with aggregation
To aggregate values like sales, use values= with the column and aggfunc= with the aggregation function.
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.
Final Answer:
pd.crosstab(df['City'], df['Product'], values=df['Sales'], aggfunc='sum') -> Option A
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 unknownstrongwhile earning +1 Grip toward your certificate.