Build a gender by product contingency table of counts in pandas
Quick Overview
Implement a pandas function that counts the rows for every combination of gender and product and returns them as a wide contingency table. It tests two-way counting in pandas, filling combinations that never occur with zero, keeping integer counts and preserving axis names.
Build a gender by product contingency table of counts in pandas
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `gender_by_product_crosstab(df)`, which returns a contingency table of row counts crossing `gender` (index) against `product` (columns).
The returned table must:
- be a DataFrame with the gender values as its index and the product values as its columns, returned as-is (no `reset_index()`);
- hold `int64` counts in every cell;
- keep the axis names `index.name = 'gender'` and `columns.name = 'product'`;
- show `0` for any combination that never occurs.
For example:
```python
df = pd.DataFrame({
'gender': ['M', 'F', 'F', 'M', 'F'],
'product': ['A', 'A', 'B', 'B', 'A'],
})
gender_by_product_crosstab(df)
# product A B
# gender
# F 2 1
# M 1 1
```
```hint Two-way counts
Each cell is the number of rows with one gender and one product. pandas has a function made for this kind of table. If you build it by grouping instead, check what a pair that never occurs turns into.
```
### What a Strong Answer Covers
- A function that returns the table with gender on the index, product on the columns, the required axis names and `int64` cells.
- How combinations that never occur end up as `0`, and why a grouping approach can turn them into NaN and change the dtype.
- What happens to rows where `gender` or `product` is missing.
- An equivalent way to build the same table, and how its output compares.
### Follow-up Questions
- How would you add row and column totals to the crosstab?
- How would you convert counts to row-wise proportions?
- How would you make every known product appear as a column, including one that no row mentions?
- How would you sum a `revenue` column in each cell instead of counting rows?
Overview: Implement a pandas function that counts the rows for every combination of gender and product and returns them as a wide contingency table. It tests two-way counting in pandas, filling combinations that never occur with zero, keeping integer counts and preserving axis names.