We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Binning

"Binning" means grouping continuous numbers into discrete categories. Say you have some temperature readings, you could "bin" them into three categories: "Cold", "Normal", and "Hot":

Other examples include:

  • Instead of raw test scores, you could "bin" them into the letter grades A, B, C, D, and F.
  • Instead of raw star ratings (3.2, 4.7...), you could use tiers (Low, Mid, Top).

So, why bin your data?

  • It simplifies analysis (patterns are easier to see in groups).
  • It creates segments for business decisions.
  • It reduces noise in the data.

The pd.cut() method is an easy way to create "bins" in a DataFrame.

Here we create a new rating_tier column set to "Low", "Mid", or "Top" based on the rating column:

# 0 up to 3 = Low
# above 3 up to 4 = Mid
# above 4 up to 5 = Top
df["rating_tier"] = pd.cut(
    df["rating"],
    bins=[0, 3, 4, 5],
    labels=["Low", "Mid", "Top"],
    include_lowest=True,
)

The include_lowest=True argument makes sure the very first edge (0) is included in the lowest bin.

Assignment

SnackStack's support team wants a quick categorical view of the device fleet for their dashboard: a temperature zone and a battery tier for every device.

Complete the categorize_devices function. It accepts a DataFrame of devices and returns a copy with two new categorical columns.

    • "Cold" (up to 5°C)
    • "Normal" (above 5 up to 25°C)
    • "Hot" (above 25°C).
    • (Be sure to include the lowest edge in the first bin)

      Use float("-inf") and float("inf") when the values are unbounded

    • "Low" (up to 20)
    • "Medium" (above 20 up to 60)
    • "High" (above 60 up to 100).
    • (Be sure to include the lowest edge in the first bin)