Zum Inhalt springen

Lektion 16 · Many Variables

Derived Features and Segments

Create derived variables and rule-based segments during exploration, compare rows on several variables with scaling, and avoid circular or leaky features.

The columns you receive are rarely the best ones for your question. A pair of timestamps becomes a duration. Orders become "orders per customer". Several measures together describe a type of user. Creating these derived variables (often called features) is a creative and useful part of EDA.

Derive variables that mean something

Good derived variables answer a plain question.

Raw columns Derived variable Question
ordered_at, delivered_at delivery_hours How long did it take?
revenue, orders average order value How much per order?
signup_date, report date tenure_days How long has this customer been here?
timestamp weekday, hour When does it happen?
price, size price per square meter Is it expensive for its size?
Python Derive durations and calendar parts

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.

These timestamps carry no time zone. With real data, find out which zone they use and whether clocks change with daylight saving time. See time zones.

Check every new column

A new column deserves the same inspection as a raw one: distribution, missing values and extremes. Ratios need special care. A denominator of zero raises an error in plain Python division, while pandas column division can produce infinity or a missing value. Decide what "no value" means.

Python Safe ratios

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.

ben has no average, not an average of zero. cho has a high average built on a single order. Keep the count beside the ratio.

Aggregate to the right grain

To describe customers, you often start with order rows and summarize each customer. pandas does this with named aggregation.

Python From orders to customer features

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.

Recency, frequency and monetary value form a classic trio for describing customers, often shortened to RFM. A fixed reference date (report_date above) keeps results repeatable.

Rule-based segments

A segment is a group of rows that share traits. Start with simple rules that people can understand.

Python Transparent segment rules

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 order of rules matters: eli has many orders but has not returned for 140 days, so the first rule labels him lapsed. Check segment sizes, test boundary cases and ask whether the thresholds fit the business.

Distance needs scaling

If you compare rows on several variables, for example to find similar customers or to cluster them, units matter. Income in currency units would swamp age in years. Standardizing each column (z-scores) puts them on comparable scales.

Scaling is a choice about importance. After standardizing, each variable gets a similar weight, which may or may not suit your question. Clustering methods such as k-means can suggest groups, but they return clusters even when the data has no natural ones. Inspect each cluster's summaries, try different settings and see whether the groups stay stable. Methods that compress many columns into a few, such as principal component analysis (PCA), help you view structure but make axes harder to explain.

Watch for circular and leaky features

Feature traps

Circular Feature contains the outcome
Future data Unknown at decision time
Sensitive May expose or discriminate
1 / 2

If you segment customers by total spend and then report that the high-spend segment spends more, you have learned nothing: it is circular. If you study cancellation and include "days since account closed", the feature reveals the answer. This is leakage: using information that would not exist at the time of the decision.

Be careful with segments based on personal traits. Sensitive attributes, or proxies for them such as postal codes, can lead to unfair treatment. Follow your privacy rules and use only what you need.

Document each feature

A short definition table prevents confusion later:

Feature Definition Missing when
delivery_hours delivered_at minus ordered_at Not yet delivered
average_order_value revenue divided by orders No orders
days_since_last report date minus last order date No orders

Add the data cutoff date and any filters, such as whether refunded orders count. Two analysts who define "active customer" differently will get different results from the same data, and both may believe they are right.

Do the segments help?

A useful segmentation is understandable (you can describe each group in one sentence), stable (most members do not jump between groups for trivial reasons), large enough to study and actionable (someone would treat the groups differently). If a segment fails these tests, simplify it.

Try it yourself

Add a "new" segment to the rule function for customers with one order in the last 10 days. Decide where the rule belongs in the order of checks, then test customers who sit exactly on each boundary.

Test features on single rows

Pick a few records and compute each new feature by hand. Include awkward ones: a customer with one order, an order placed just before midnight, a refund and a record with a missing timestamp. Compare your answers with the code. This quick test catches reversed subtractions, wrong units and filters that silently drop rows. After a change to the definition, run the same examples again.

A common mistake

Do not overwrite a raw column with its derived version. If you later find a mistake in the formula, you need the original to rebuild it. Give the new column a clear name that includes the unit, such as delivery_hours, so that nobody has to guess what a bare number means.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. A customer has zero orders. What is their average order value?

    Dividing by zero has no meaningful result, and zero would be misleading.
  2. 2. Why use a fixed reference date for days since last order?

    Using the current date would change the output every day.
  3. 3. Why standardize variables before measuring distance between rows?

    Scaling puts columns on comparable scales, which is itself a weighting choice.
  4. 4. What is leakage?

    Leaky features make results look better than they could be in reality.

Summary

  • Derive variables that answer plain questions, and inspect them like raw data.
  • Handle zero denominators and keep counts beside ratios.
  • Aggregate to the grain you need and use fixed reference dates.
  • Start with transparent segments; treat clusters as suggestions to test.
  • Watch for circular logic, leakage and sensitive attributes.

Next: Exploring Time Series

Dein Fortschritt wird in diesem Browser gespeichert. Kein Konto nötig.