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:
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: int64Each 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
MediumA 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.
- Add each member's age group as a column
group. - Print each group's member count,
childfirst. - Print the mean
visitsof 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.5Try it yourself
import pandas as pd
members = pd.read_csv("members.csv")
group = input()
# Write your code below
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Statistics for ML
1Center and Spread
Mean and MedianPercentiles and QuartilesVariance and StdSample or Population?The Most Common ValueRecap: Delivery Times4Samples and Populations
Population and SampleSample Means VaryThe Sampling DistributionBigger Samples, Less NoiseRecap: Polling a Town2Distributions
Density HistogramsShapes of DataThe Normal CurveThe 68-95-99.7 RuleZ-ScoresRecap: Battery Life3Probability by Simulation
Probability as FrequencyThe Law of Large NumbersSums of DiceExpected ValueConditional ProbabilityRecap: Dice Stall Odds6Relationships
Reading Scatter PlotsCorrelationCorrelation MatrixCorrelation HeatmapsCorrelation Is Not CauseRecap: Ice Cream and SunPractice on your own: Online Python compiler