Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas pd.cut() function

Pandas pd.cut() function

Pandas Universal Functions Common Pandas functions


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

- Type: array-like object, such as a list, Series, array, etc. - Description: Continuous numeric data to be binned. - 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). - Type: boolean. - Description> Whether to use right-closed intervals. Defaults to 'True' (i.e., the [a, b] form). If set to 'False', the intervals are left-closed and right-open (a, b]. - Type: array or None. - Description: Specify custom labels for each interval. If not specified, the interval representation is used (e.g., "(0, 10]"). - Type> boolean. - Description> If 'True', the returned result includes the bin boundary values. Defaults to 'False'. - Type> boolean. - Description> If 'True', the first interval includes the left boundary. Defaults to 'False'.

Function description


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

]

)

print

(

"=== Original scores ==="

)

print

(

scores

)

2. Divide the scores into 3 equal-width intervals

result

=

pd.

cut

(

scores

,

bins

=

3

)

print

(

"\n=== pd.cut(scores, bins=3) equal-width binning ==="

)

print

(

result

)

3. View the bin boundary values

result_bins

=

pd.

cut

(

scores

,

bins

=

3

,

retbins

=

True

)

print

(

"\n=== Return bin boundaries ==="

)

print

(

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:

  1. bins=3 means automatically dividing the data into 3 equal-width intervals.
  2. Pandas automatically computes interval boundaries based on the minimum and maximum values of the data.
  3. The returned type is Categorical, and each value is an Interval object.
  4. 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

)

print

(

"=== Original scores ==="

)

print

(

scores.

values

)

print

(

"\n=== Binning result ==="

)

print

(

result

)

Count the number of people at each level

print

(

"\n=== Score distribution statistics ==="

)

print

(

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:

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

)

print

(

"=== Default right-closed interval [a, b] ==="

)

print

(

result1

)

Left-closed right-open interval (a, b]

result2

=

pd.

cut

(

data

,

bins

=

4

,

right

=

False

)

print

(

"\n=== Left-closed right-open interval (a, b] ==="

)

print

(

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:


Notes

Important note:

  • If there are values in the data that exceed the bins specified range, it will produce NaN
  • bins boundaries must be monotonically increasing
  • When using custom labels, the number of labels must be one less than the number of boundaries
  • The binned result is of Categorical type and can be processed with string methods

  • Python math Module Common Pandas functions