pd.cut turns a numeric or timedelta Series into interval-based categories. Define cut points, provide one fewer labels than cut points, and assign the result wherever a compact analytical grouping is useful—such as short, medium, and long taxi rides. section 1.27 section 10.2
For numeric bins, boundaries are exclusive on the left and inclusive on the right: a bin from 2 to 10 contains values greater than 2 and up to 10. Use include_lowest=True when the first boundary should include the series minimum. pd.cut is a top-level pandas function, not a Series method. section 1.27
Classify taxi distances
Create a distance category, then summarize it. Four boundaries create three labeled groups; using the column minimum and maximum covers the observed range. pd.cut(df['trip_distance'], [df['trip_distance'].min(), 2, 10, df['trip_distance'].max()], labels=['short', 'medium', 'long'], include_lowest=True) Assign this result to trip_distance_group to retain the categories as a DataFrame column. Grouping by that column can then compare mean passenger counts across distance bands. section 6.6
pd.cut(s,
bins=[0, 2, 10, s.max()],
include_lowest=True,
labels=['short', 'medium', 'long'])
This compact call bins a Series at 0, 2, 10, and its maximum, includes the lowest value, and replaces distances with three ride labels. section 1.27
Bins need values comparable with the input Series. For trip durations, convert textual limits such as “10 minutes” and “1 hour” to timedelta objects before cutting. The resulting category column can drive groupby calculations just like a column of existing labels. section 10.2 section 6.6
Useful follow-up checks include:
- Count observations in each interval with value_counts(). section 1.27
- Filter to a subgroup whose Series shares the same index, then count its short, medium, and long values. section 1.29
- Try bins=3 when equal automatic bin creation is the question instead of explicit business-defined intervals. section 1.29
