Saltar al contenido

Lección 13 · Two Variables

Comparing Two Categorical Variables

Explore two categorical variables with contingency tables, row and column percentages, expected counts and clear charts, and read the base correctly.

Does the cancellation rate differ by plan? Do mobile and desktop visitors choose different payment methods? When both variables are categories, you count combinations. The result is a contingency table, also called a cross-tabulation or crosstab.

Build a contingency table

Each cell counts the rows with one value of the first variable and one value of the second. The totals along the edges are the marginal totals.

Python A crosstab in plain Python

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Raw counts show that more basic customers left. But there are also twice as many basic customers. You need percentages.

Three kinds of percentages

The same cell can become three different percentages.

Basic customers who left: 40

Row: 20% Of basic customers, who left?
Column: 80% Of leavers, who was basic?
Total: 13% Of everyone, who is both?

Choose the base that matches your question

1 / 2

All three are true, and they answer different questions. "80% of leavers were on the basic plan" sounds alarming, but basic customers are two thirds of everyone. To compare plans, use the row percentage: 20% of basic customers left versus 10% of pro customers.

A useful habit is to condition on the variable you think of as the starting point (plan) and compare the outcome (left) across its values. This is a way to organize the comparison, not proof that the plan causes leaving.

pandas crosstab

pd.crosstab builds these tables. The normalize argument takes "index" for row shares, "columns" for column shares or "all" for shares of the total.

Python Counts, then row shares

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In SQL

Conditional aggregation gives rates per group in one query.

SQL Leaving rate per plan

Press Run (or Ctrl + Enter) to see the result here.

The average of a 0/1 column is the share of ones, as long as there are no missing values.

Independence and expected counts

If the two variables were unrelated (independent), each plan would have about the same outcome shares. You can compute the expected count for each cell as row total times column total divided by the grand total. Gaps between observed and expected counts show where the association is.

Python Observed versus expected

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Cramér's V summarizes the strength of association from 0 to 1. The short formula works here because the table has two rows and two columns. For bigger tables you also divide by the smaller of the number of rows or columns, minus 1, before taking the square root. The chi-square statistic itself grows with sample size, so it does not measure strength. Chi-square tests address whether a pattern could easily arise by chance.

Rate differences and ratios

For a yes/no outcome, you can say "the rate is 10 percentage points higher" or "the rate is twice as high". Both describe 20% versus 10%. A ratio can sound dramatic when the base is tiny: 0.2% versus 0.1% is also "twice". Give both rates.

Charts

A grouped bar chart compares shares side by side. A 100% stacked bar shows composition per group, but only the segments that share a baseline are easy to compare. A heatmap of row shares helps when there are many categories. Show counts as labels or in a table nearby.

Sparse tables with many categories contain tiny cells, which make shares jump wildly. Merge categories for a clear reason, or report counts only. Also avoid publishing very small cells about people, since they may identify individuals.

More than two categories

With a larger table, such as five plans by four outcomes, start with row percentages and highlight the cells that differ most from the overall column share. Keep the "All customers" row visible as a reference. If one outcome is very common, small percentage gaps there may involve more people than large relative gaps in a rare outcome, so look at counts too.

Think about which categories can be merged without losing meaning. "Left for price" and "left for features" are both leaving, but merging them removes the reason, which may be the interesting part.

Writing the result

A clear sentence names both rates and both bases: "40 of 200 basic customers (20%) left, compared with 10 of 100 pro customers (10%)." It does not say that upgrading would halve the risk. Customers who choose the pro plan may differ in many ways, such as company size or how long they have used the product.

Try it yourself

In the pandas example, switch normalize="index" to "columns" and then to "all". For each table, write the question that the top-left to bottom-right cells answer. Then change the pro group to 20 customers with 2 leavers and discuss how much you trust its 10% rate now.

Check what is missing

Add a row or column for unknown values before you drop them. If customers with an unknown plan leave much more often than others, the gap itself may be informative. Perhaps the plan field is cleared when an account closes. That would be a recording rule, not customer behavior, and it could distort every rate in the table. Ask the data owner how each field changes over a record's life.

Time matters

A cancellation rate needs a time window. Customers who joined last week have had little chance to leave, so a plan that recently attracted many new customers may look unusually sticky. Compare customers who have had the same amount of time, as described in the lesson on cohorts.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. With plans in rows, which percentage compares leaving rates between plans?

    Row percentages show, within each plan, the share that left.
  2. 2. How is an expected count under independence computed?

    It applies the overall outcome share to each group's size.
  3. 3. A rate rises from 10% to 20%. Which description is correct?

    The absolute change is 10 points; the relative change is 100%.
  4. 4. Why can the chi-square statistic mislead as a measure of strength?

    Use rates and an association measure such as Cramer's V to describe strength.

Summary

  • A contingency table counts combinations of two categories.
  • Row, column and total percentages answer different questions.
  • Expected counts show where observed data departs from independence.
  • Report both rates, with percentage-point differences or ratios.
  • Be careful with sparse tables and small cells about people.

Next: Correlation Matrices and Pair Plots

Tu progreso se guarda en este navegador. No necesitas una cuenta.