Binning Values

Turning a measurement into a band you can count.

cut divides a range into labelled bands

Grades, age groups and price brackets are all the same operation: choose the edges, name the bands.

import pandas as pd

scores = pd.Series([95, 82, 71])
bands = pd.cut(scores, bins=[0, 79, 89, 100], labels=["C", "B", "A"])
print(bands.tolist())

The edges are a decision

Whether 89 is a B or an A is your call, and cut makes you write it down. right=True, the default, means the upper edge belongs to the band.

import pandas as pd

s = pd.Series([89])
print(pd.cut(s, bins=[0, 89, 100], labels=["low", "high"]).tolist())

Exercise

Try It Yourself

Write grade(scores) that returns a list of letter grades: 90 and above is an A, 80 to 89 a B, 70 to 79 a C, and anything below that an F.

Press Run to see output

Check Your Understanding