Aller au contenu

Leçon 10 · One Variable

Transforming and Binning Data

Use log transforms, rates, standard scores and binning to make patterns visible, and learn what each change does to your summaries and your conclusions.

Some data is hard to see in its original form. One huge customer squashes everyone else into a corner of the chart. Large cities have more of almost everything. Ages with sixty different values make a long table. A transformation changes how values are expressed so that structure becomes visible.

Transform to understand, not to hide. Keep the original column, name the new one clearly, and remember that a summary of transformed data means something different.

The log transform

A logarithm turns multiplication into addition. On a base-10 log scale, 10, 100 and 1,000 are equally spaced. This spreads out small values and pulls in large ones, which helps with strongly right-skewed data such as revenue or population.

Python Raw values and log 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.

If you average the logs and transform back, you get the geometric mean, not the ordinary mean. It can be a reasonable "typical value" for ratio-like data, but you cannot multiply it by the count to rebuild a total.

Zeros and negative values

The logarithm is defined only for positive numbers. Common options are:

  • Analyze zeros as their own group, then log the positive values.
  • Use log1p(x), which means log(1 + x), for non-negative counts. Its effect depends on the unit of x.
  • Use a different transform, such as a square root for counts.
Python Handle zeros openly

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.

Do not silently drop zeros just to make a log chart work. "Bought nothing" can be the most important group.

Log axes on charts

Often you do not need to change the data. You can change the axis and keep readable labels. For a histogram on a log axis, the bin edges should grow by a constant factor.

Python Linear and logarithmic views

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.

Always say on the chart or in its caption that an axis is logarithmic. Equal distances on it mean equal ratios, not equal differences.

Rates and ratios

Raw counts often just measure size. To compare fairly, divide by an exposure: people, visits, hours or kilometers.

Python Counts versus rates

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 city with the fewest incidents has the highest rate. Check that the numerator and denominator cover the same population and period. Rates from small denominators jump around, so show the counts as well.

Standard scores

A z-score is (value minus mean) divided by standard deviation. It says how many standard deviations a value is from the mean, which helps you compare positions in variables with different units. It changes the center and scale but not the shape: skewed data stays skewed. A z-score also depends on the mean and standard deviation, which extremes can distort.

Binning

Binning turns numbers into ranges such as age groups.

Python Bins with clear edges

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.

right=False puts age 18 into "18-24". Test the values that sit exactly on edges. pd.cut uses edges that you choose. pd.qcut creates bins with roughly equal counts, as far as ties allow. See binning in pandas.

Binning trade-offs

Gains Readable groups and tables
Losses Detail inside each bin
Risk Edges can change the story
1 / 2

Do not move bin edges until a difference looks impressive. Choose edges for a reason (policy ages, price tiers, quantiles) and check that the conclusion survives reasonable alternatives.

Reading results after a transform

Always translate transformed results back into plain language. A difference of 1 on a base-10 log scale means "ten times as much". A z-score of 2 means "two standard deviations above this group's mean", which says nothing about whether the value is good, bad or rare in other groups.

Keep a note of each derived column: its formula, how it treats zeros and gaps, and the data used to compute any constants. A z-score computed from March data differs from one computed from the whole year.

Which transformation?

Problem Option to try
Strong right skew, all positive Log scale
Counts with many zeros Separate zeros, or log1p
Groups of very different size Rates or shares
Different units to compare Standard scores or ranks
Too many distinct values for a table Bins

Try the simplest option first, which is often just a better axis range or a log axis.

Try it yourself

Take the revenue list from the first example and add a value of 0. See which line of the code fails and why. Then rewrite the example so that it reports the number of zeros first and applies the log only to positive values.

Test your conclusion both ways

Look at your main comparison on the original scale and on the transformed scale. A gap between two groups can look small on one and large on the other, because one scale measures differences and the other measures ratios. Neither is wrong. Decide which one matches the question. A finance team that cares about total money usually needs original units, while a question about relative growth fits ratios better. State which you used.

Common mistakes

Watch for bins with unequal widths drawn as if they were equal, edges that leave some values outside every bin and rates whose denominator comes from a different period. In pandas, pd.cut gives a missing value to anything outside your edges, so count the gaps after binning and compare them with the gaps before it.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What do equal distances on a log axis represent?

    From 10 to 100 looks as wide as from 100 to 1,000, because both multiply by ten.
  2. 2. What does a z-score transformation do to a skewed distribution?

    Subtracting and dividing by constants does not change the shape.
  3. 3. City A has more incidents than city B. What else do you need to compare risk fairly?

    Rates adjust for differences in size.
  4. 4. What is the difference between pd.cut and pd.qcut?

    qcut is based on quantiles.

Summary

  • Transform to reveal structure, and keep the original values.
  • Logs suit positive, right-skewed data; treat zeros openly.
  • Rates with matching denominators allow fairer comparisons than raw counts.
  • Z-scores rescale without changing shape.
  • Binning simplifies but loses detail, so test edges and alternatives.

Next: Relationships Between Two Numeric Variables

Votre progression est enregistrée dans ce navigateur. Aucun compte nécessaire.