cut() groups values by their actual magnitude into bins defined by explicit edge values, or a single integer, which creates that many equal-width bins spanning the data's range, returning a Categorical Series showing which bin each value fell into. This is fundamentally different from just splitting data into equal-sized groups — a bin might end up containing very few, or very many, values, since the bins are defined by value ranges, not by how many data points happen to fall into each one.
1Understanding pd.cut()
cut() groups values by their actual magnitude into bins defined by explicit edge values, or a single integer, which creates that many equal-width bins spanning the data's range, returning a Categorical Series showing which bin each value fell into. This is fundamentally different from just splitting data into equal-sized groups — a bin might end up containing very few, or very many, values, since the bins are defined by value ranges, not by how many data points happen to fall into each one.
cut() creates bins with equal width, the same size range for each bin, which can lead to very uneven bin populations if the data isn't evenly spread — use qcut() instead when you specifically want bins with an equal number of values in each one.
import pandas as pd
ages = pd.Series([5, 17, 25, 45, 70])
bins = [0, 18, 65, 100]
labels = ["Minor", "Adult", "Senior"]
print(pd.cut(ages, bins=bins, labels=labels))2Practical Example
Here is a real-world application of pd.cut() showing how it is used in production Pandas code.
import pandas as pd
scores = pd.Series([10, 20, 85, 90, 95])
print(pd.cut(scores, bins=3))3Best Practices
Follow these guidelines when working with pd.cut():
1. Pass explicit bin edges for meaningful, real-world categories, like age brackets, rather than relying on automatic equal-width bins that may not align with meaningful boundaries
2. Pass labels explicitly to give each resulting bin a readable name, instead of the default interval-notation labels
3. Use qcut() instead of cut() when you want each bin to contain roughly the same number of data points, rather than the same range of values
Tip: cut() creates bins with equal width, the same size range for each bin, which can lead to very uneven bin populations if the data isn't evenly spread — use qcut() instead when you specifically want bins with an equal number of values in each one.
import pandas as pd
ages = pd.Series([5, 17, 25, 45, 70])
bins = [0, 18, 65, 100]
labels = ["Minor", "Adult", "Senior"]
print(pd.cut(ages, bins=bins, labels=labels))