Menu
CoddyTech

Binning Numbers

Part of the Statistics for ML section of Coddy's Machine Learning journey. Lesson 54 of 64.

An airline charges a bag by its weight class, not by the gram. Binning turns numbers into ranges, called bins, for when only the range matters:

A number line from 0 to 32 kg cut at 7 and 23 into three shaded bins, cabin, standard and heavy, with six bags as dots: 5.5 and 7.0 in cabin, 12.4, 18.2 and 23.0 in standard, 30.5 in heavy

pd.cut takes the values, the edges and one label per bin:

bags = pd.DataFrame({"kg": [5.5, 23.0, 18.2, 30.5, 7.0, 12.4]})
bags["class"] = pd.cut(bags["kg"], bins=[0, 7, 23, 32],
                       labels=["cabin", "standard", "heavy"])
print(bags["class"].value_counts().sort_index())

This prints:

class
cabin       2
standard    3
heavy       1
Name: count, dtype: int64

Each bin includes its right edge, so 7.0 kg is still cabin, and a value outside the edges becomes NaN.

.sort_index() lists the bins in their own order, lightest first.

challenge icon

Challenge

Medium

A zoo groups the members in members.csv by age: child up to 12, teen 13 to 17, adult 18 to 64, senior 65 to 100. The program reads a group.

  1. Add each member's age group as a column group.
  2. Print each group's member count, child first.
  3. Print the mean visits of the group read, to 2 decimals.

For a smaller zoo and the input teen:

group
child     1
teen      2
adult     2
senior    1
Name: count, dtype: int64
Mean visits for teen: 10.5

Try it yourself

import pandas as pd

members = pd.read_csv("members.csv")
group = input()

# Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Statistics for ML

Practice on your own: Online Python compiler