Pandas pd.cut() function
pd.cut() is a function in the Pandas library used to **bin continuous data (Binning)**. It divides numeric data into discrete categories according to specified intervals, making it very suitable for grouped statistics and visualization in data analysis.
Binning is very common in data analysis, for example dividing age into "teenager", "middle-aged", and "senior", or dividing scores into "fail", "pass", "good", and "excellent".
Word meaning: cut means "cutting"; here it refers to "cutting" continuous data intervals into multiple discrete intervals.
Basic syntax and parameters
pd.cut() is a top-level function in the Pandas library used to discretize continuous variables.
Syntax format
pd.cut(x, bins, right=True, labels=None, retbins=False, precision=3, include_lowest=False)
Parameter Description
- Parameters:
x - Type: array-like object, such as a list, Series, array, etc.
- Description: Continuous numeric data to be binned.
- Parameters:
bins - Type: integer, scalar (interval boundaries), or IntervalIndex.
- Description: The binning scheme. Can be an integer (indicating how many equal-width bins to create) or a list (specifying the exact interval boundaries).
- Parameters:
right - Type: boolean.
- Description> Whether to use right-closed intervals. Defaults to
True(i.e., the [a, b] form). If set toFalse, the intervals are left-closed and right-open (a, b].
- Parameters:
labels - Type: array or None.
- Description: Specify custom labels for each interval. If not specified, the interval representation is used (e.g., "(0, 10]").
- Parameters:
retbins - Type> boolean.
- Description> If
True, the returned result includes the bin boundary values. Defaults toFalse。
- Parameters:
include_lowest - Type> boolean.
- Description> If
True, the first interval includes the left boundary. Defaults toFalse。
Function description
- Return Value: Returns a Series of Categorical type, where each value corresponds to the interval it belongs to.
- effect: Maps continuous numeric values to discrete categories (intervals).
Example
Let us thoroughly master pd.cut() through a series of examples from simple to complex.
Example 1: Basic usage - equal-width binning
Example
import
pandas
as
pd
import
numpy
as
np
1. Create numeric data
scores
=
pd.
Series
(
[
55
,
70
,
82
,
45
,
90
,
65
,
78
,
88
,
92
,
58
]
)
(
"=== Original scores ==="
)
(
scores
)
2. Divide the scores into 3 equal-width intervals
result
=
pd.
cut
(
scores
,
bins
=
3
)
(
"\n=== pd.cut(scores, bins=3) equal-width binning ==="
)
(
result
)
3. View the bin boundary values
result_bins
=
pd.
cut
(
scores
,
bins
=
3
,
retbins
=
True
)
(
"\n=== Return bin boundaries ==="
)
(
f
"Bin boundaries: {result_bins[1]}"
)
Expected output:
=== 原始分数 ===
0 55
1 70
2 82
3 45
4 90
5 65
6 78
7 88
8 92
9 58
=== pd.cut(scores, bins=3) 等宽分箱 ===
0 (44.667, 60.667]
1 (60.667, 76.333]
2 (76.333, 92.0]
3 (44.667, 60.667]
4 (76.333, 92.0]
5 (60.667, 76.333]
6 (60.667, 76.333]
7 (76.333, 92.0]
8 (76.333, 92.0]
9 (44.667, 60.667]
dtype: category
Categories (3, interval[float64]): [(44.667, 60.667] < (60.667, 76.333] < (76.333, 92.0]
=== 返回分箱边界 ===
分箱边界: [44.667 60.667 76.333 92. ]
Code analysis:
bins=3means automatically dividing the data into 3 equal-width intervals.- Pandas automatically computes interval boundaries based on the minimum and maximum values of the data.
- The returned type is Categorical, and each value is an Interval object.
- Right-closed intervals are used by default, i.e., the (a, b] form.
Example 2: Custom interval boundaries
In practice, we often need to customize bin boundaries based on business requirements.
Example
import
pandas
as
pd
import
numpy
as
np
Create score data
scores
=
pd.
Series
(
[
55
,
70
,
82
,
45
,
90
,
65
,
78
,
88
,
92
,
58
,
73
,
67
,
81
,
49
,
95
]
)
Custom bin boundaries: fail, pass, good, excellent
bins
=
[
0
,
60
,
75
,
90
,
100
]
labels
=
[
'Fail'
,
'Pass'
,
'Good'
,
'Excellent'
]
result
=
pd.
cut
(
scores
,
bins
=
bins
,
labels
=
labels
,
include_lowest
=
True
)
(
"=== Original scores ==="
)
(
scores.
values
)
(
"\n=== Binning result ==="
)
(
result
)
Count the number of people at each level
(
"\n=== Score distribution statistics ==="
)
(
result.
value_counts
(
)
.
sort_index
(
)
)
Expected output:
=== 原始成绩
[55 70 82 45 90 65 78 88 92 58 73 67 81 49 95]
=== 分箱结果
0 及格
1 良好
2 良好
3 不及格
4 优秀
...
12 良好
13 不及格
14 优秀
dtype: category
Categories (4, interval[int64]): [不及格 < 及格 < 良好 < 优秀]
=== 成绩分布统计
不及格 3
及格 4
良好 5
优秀 3
dtype: int64
Code analysis:
bins=[0, 60, 75, 90, 100]defines 4 intervals: [0-60], (60-75], (75-90], (90-100]labelsthe parameter assigns intuitive Chinese labels to each intervalinclude_lowest=Trueensure the first interval includes the left boundary 0value_counts()makes it easy to count the number of people at each level
Example 3: Using right-closed/left-closed intervals
Example
import
pandas
as
pd
import
numpy
as
np
Test Data
data
=
pd.
Series
(
[
10
,
20
,
30
,
40
,
50
]
)
Default right-closed interval [a, b]
result1
=
pd.
cut
(
data
,
bins
=
4
)
(
"=== Default right-closed interval [a, b] ==="
)
(
result1
)
Left-closed right-open interval (a, b]
result2
=
pd.
cut
(
data
,
bins
=
4
,
right
=
False
)
(
"\n=== Left-closed right-open interval (a, b] ==="
)
(
result2
)
Expected output:
=== 默认右闭区间 [a, b]
0 (7.5, 17.5]
1 (17.5, 27.5]
2 (27.5, 37.5]
3 (37.5, 47.5]
4 (47.5, 57.5]
dtype: category
=== 左闭右开区间 (a, b]
0 [10, 17.5)
1 [17.5, 27.5)
2 [27.5, 37.5)
3 [37.5, 47.5)
4 [47.5, 57.5)
dtype: category
Code analysis:
- Right-closed intervals are used by default
[a, b], i.e., including the right boundary - Settings
right=Falsechange to left-closed right-open intervals[a, b) - Whether an interval is open or closed affects how boundary values are classified
Notes
Important note:
bins specified range, it will produce NaNbins boundaries must be monotonically increasing
Common Pandas functions