跳到正文

第 9 课 · One Variable

Exploring Categorical Variables

Explore categorical columns with frequency tables and shares, clean inconsistent labels, handle rare and high-cardinality categories, and chart them well.

A categorical variable takes values from a set of labels: country, plan type, error code, favorite drink. You cannot average these labels, but you can count them. Those counts often reveal both important facts and messy data problems.

Frequency tables

Start with the count and share of each category, sorted from largest to smallest. If there are missing values, show them as their own row.

Python Counts, shares and cumulative 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.

The cumulative column shows concentration: the first two categories cover most tickets. When a few categories dominate, you know where to look first.

In pandas, value_counts does the same work. Add normalize=True for shares and dropna=False to keep missing values visible.

Python value_counts with missing values

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.

Look at the two outputs closely. The second one leaves out missing values by default, so its shares are based on only the known plans. Say which base you use.

Clean up labels

Free text and merged sources often spell one thing in several ways.

Python Normalize category labels

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.

The function marks unknown labels such as Peruu as UNMAPPED instead of guessing. Keep the raw column, store the cleaned version in a new one, and save the mapping so that others can review it.

Cardinality

Cardinality is the number of distinct values.

How many categories?

One No variation to study
A few Count and chart all
Hundreds Show the top ones
One per row Likely an ID or free text
1 / 2

For high-cardinality columns such as product codes or search terms, study the long tail: how many categories occur only once, and how much of the total the top ten cover. You can sometimes group them at a higher level, such as product family.

Rare categories

Rare categories make charts crowded and rates unstable. A common option is to merge them into "Other".

Python Group rare categories

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.

Write down the threshold and which labels went into "Other". A small group can matter a lot: a rare error code may be the one that loses money. Group for display, but keep the detail in your data.

Ordinal categories

For ordered categories such as "low, medium, high", keep the natural order in tables and charts. Sorting by count or alphabet hides the pattern. For survey scales, look at both ends. An average near the middle can mean that most people are neutral, or that half love and half dislike the product.

Charts for categories

A bar chart is usually a good choice. Use horizontal bars when labels are long, sort by value for nominal data, and start the axis at zero, because bar length stands for the count.

Python Sorted horizontal bars

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.

Pie charts make it hard to compare similar slices, especially when there are many. See choosing a chart for guidance.

Class imbalance

When one category covers almost everything, such as 99% "no fraud", the data is imbalanced. Note it during EDA. It affects how you compare groups, how many rare examples you really have and how you judge any later model. A rule that always says "no fraud" would be right 99% of the time and still be useless.

A percentage without its count can mislead. "50% of users from region X complained" sounds serious until you learn that region X has two users. Show counts next to shares.

Categories over time

Category lists change. A product is renamed, two departments merge or a new payment method appears. A frequency table for the whole period hides this. Count categories per month and look for labels that appear or vanish suddenly. If "mobile app" disappears in the same month that "app" appears, you are probably looking at one category with two names.

Multiple answers in one cell

Some columns hold several values at once, such as "email;phone". Counting the raw strings treats every combination as its own category. Split the values into one row per choice before counting, and remember that shares can then add up to more than 100% of respondents. Say whether your percentages are based on answers or on people.

Try it yourself

In the first example, add 12 tickets with a missing category and decide how to show them. Compute the share of billing tickets twice, once with all tickets as the base and once with only categorized tickets. Write one sentence for each result that makes its base clear.

Ask where labels come from

A dropdown list, a free text box and a software default produce very different data. With a dropdown, check whether the first option is suspiciously popular, because some people accept whatever is preselected. With free text, expect typos and many rare values. With a system default such as "general" or "other", ask how often nobody made a real choice. A large "other" group is a finding: the categories may no longer describe what happens. Read a sample of those records if you are allowed to, and look for a missing category.

Write the finding

State the count, the share and the base together, for example: "Billing was the most common ticket category, with 42 of 100 tickets." If the base excludes uncategorized tickets, say so in the same sentence. Avoid ranking tiny differences. Two categories separated by one or two cases are effectively tied for most practical purposes, and their order may change next week.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. By default, what base does pandas value_counts(normalize=True) use?

    Missing values are dropped unless you pass dropna=False.
  2. 2. A column has a different value in every row. What is it most likely to be?

    One distinct value per row gives nothing to group by in its raw form.
  3. 3. What is a good way to handle unknown labels during cleaning?

    Guessing hides problems; a visible flag keeps them reviewable.
  4. 4. Why should the axis of a bar chart of counts start at zero?

    A truncated axis makes small differences look large.

Summary

  • Build frequency tables with counts and shares, including missing values.
  • Normalize spellings with a reviewed mapping and keep the raw column.
  • Check cardinality, long tails and rare categories before you group them.
  • Keep ordinal order; use sorted bars from zero for nominal data.
  • Show counts with percentages and note class imbalance.

Next: Transforming and Binning Data

你的学习进度保存在此浏览器中,无需账号。