We use crosstab() to see how two or more groups relate by counting how often their values appear together. It helps us understand connections in data easily.
crosstab() for cross-tabulation in Pandas
import pandas as pd # Basic crosstab syntax df_crosstab = pd.crosstab(index=data['column1'], columns=data['column2'], margins=False, normalize=False)
index is the row variable, columns is the column variable.
margins=True adds totals for rows and columns.
import pandas as pd # Example data data = pd.DataFrame({ 'Gender': ['Male', 'Female', 'Female', 'Male'], 'Product': ['A', 'B', 'A', 'B'] }) # Crosstab of Gender vs Product result = pd.crosstab(index=data['Gender'], columns=data['Product']) print(result)
import pandas as pd # Empty data example data_empty = pd.DataFrame({'A': [], 'B': []}) result_empty = pd.crosstab(index=data_empty['A'], columns=data_empty['B']) print(result_empty)
import pandas as pd # Single element data data_single = pd.DataFrame({'A': ['X'], 'B': ['Y']}) result_single = pd.crosstab(index=data_single['A'], columns=data_single['B']) print(result_single)
import pandas as pd # Using margins to add totals result_margins = pd.crosstab(index=data['Gender'], columns=data['Product'], margins=True) print(result_margins)
This program shows how many products each gender bought and includes totals for rows and columns.
import pandas as pd # Create sample data sales_data = pd.DataFrame({ 'Customer': ['Alice', 'Bob', 'Charlie', 'Diana', 'Evan', 'Fiona'], 'Gender': ['Female', 'Male', 'Male', 'Female', 'Male', 'Female'], 'Product': ['Book', 'Pen', 'Book', 'Pen', 'Notebook', 'Book'] }) print('Original Data:') print(sales_data) # Create crosstab to count products bought by gender product_gender_crosstab = pd.crosstab(index=sales_data['Gender'], columns=sales_data['Product'], margins=True) print('\nCrosstab of Product by Gender with Totals:') print(product_gender_crosstab)
Time complexity: O(n), where n is the number of rows in the data.
Space complexity: Depends on the number of unique values in the index and columns.
Common mistake: Forgetting to specify the correct columns for index and columns, which can lead to confusing results.
Use crosstab() when you want to count occurrences between categories. For more complex aggregation, consider pivot_table().
crosstab() counts how often values from two columns appear together.
It helps compare groups easily with simple tables.
You can add totals with margins=True for better summary.
Practice
pandas.crosstab() function primarily do?Solution
Step 1: Understand the purpose of crosstab()
Thecrosstab()function creates a table showing frequency counts of combinations of values from two or more columns.Step 2: Compare with other options
Sorting, calculating mean, and filtering are different operations not done bycrosstab().Final Answer:
Counts how often values from two columns appear together -> Option CQuick Check:
crosstab() = frequency count [OK]
- Confusing crosstab with sorting or filtering
- Thinking crosstab calculates averages
- Assuming crosstab modifies original data
df?Solution
Step 1: Recall correct crosstab syntax
The correct syntax ispd.crosstab(df['A'], df['B'])where you pass two series as arguments.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.Final Answer:
pd.crosstab(df['A'], df['B']) -> Option BQuick Check:
pd.crosstab(series1, series2) = correct syntax [OK]
- Calling crosstab as a DataFrame method
- Passing multiple columns as a tuple incorrectly
- Using wrong parameters like axis
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'])?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 AQuick Check:
Count values by groups = Preference Coffee Tea Gender F 1 2 M 1 1 [OK]
- Mixing up row and column labels
- Counting values incorrectly
- Assuming missing pairs have counts > 0
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?
Solution
Step 1: Check parameter names for crosstab()
The correct parameter to name the totals row/column ismargins_name, notmargin_name.Step 2: Identify the cause of error
Usingmargin_namecauses a TypeError because it's an unexpected keyword argument.Final Answer:
The parameter name should be margins_name, not margin_name -> Option DQuick Check:
Correct parameter is margins_name [OK]
- Misspelling parameter names
- Thinking crosstab requires numeric columns
- Forgetting parentheses in print (Python 3)
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?Solution
Step 1: Understand crosstab with aggregation
To aggregate values like sales, usevalues=with the column andaggfunc=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 AQuick Check:
Use values= and aggfunc= for aggregation [OK]
- Passing column name as string instead of series
- Omitting aggfunc for aggregation
- Expecting crosstab to sum without values parameter
Ready to prove it?
Pass the test and this pattern moves unknown
