A survey recorded each person's age. For a report you want to know how many people fall in each age band, and a band that nobody falls in must still be listed, with a count of zero.
Write count_by_band(df, edges, labels).
df has a numeric column age, which may contain missing values. edges is a list of numbers in increasing order, and labels is a list of band names with one name fewer than there are edges. Band number has the name labels[i] and holds the ages with
So each band includes its lower edge and stops just before its upper edge. With edges [0, 18, 35], an 18-year-old belongs to the second band.
Return a new DataFrame with two columns:
band: the band names, as text, in the order of labelscount: how many rows of df fall in that bandThere is exactly one row per band, including bands with a count of 0.
groupby, pass observed=False. Without it, pandas 2 warns and newer versions leave the empty bands out. value_counts() on the binned column lists every band without any extra argument.df. If you want to store the bands in a column, add it to a copy (df.copy()), not to df itself.