Pandas pd.qcut() function
pd.qcut() is a function in the Pandas library used tobin by quantilesfunction. It divides data into groups of equal size, with each bin containing roughly the same number of data points.
The difference between pd.cut(), which uses equal-width bins,pd.qcut() ensures an equal amount of data in each interval, making it ideal for skewed distributions or cases where you want to split by the data's natural quantiles.
Word meaning: qcut the "q" stands for "quantile", meaning to "cut" the data by quantiles.
Basic syntax and parameters
pd.qcut() is a top-level function of the Pandas library used for quantile-based discretization.
Syntax format
pd.qcut(x, q, labels=None, retbins=False, precision=3, duplicates='raise')
Parameter Description
- Parameters:
x - Type: array-like object, such as a list, Series, array, etc.
- Description: Continuous numeric data to be binned.
- Parameters:
q - Type: an integer or an array of quantiles.
- Description: the number of bins or the specific quantiles. If an integer n is given, the data is split into n equal-sized groups (each containing about 1/n of the data). It can also be an array of quantiles (e.g., [0, 0.25, 0.5, 0.75, 1.0]).
- Parameters:
labels - Type: array or None.
- Description: custom labels for each interval. If not specified, the quantile intervals themselves are used (e.g., "(0, 25]").
- Parameters:
retbins - Type: boolean.
- Description> If
True, the returned result includes the bin boundary values. Defaults toFalse。
-
Parameters:
duplicates 类型: 字符串('raise' 或 'drop')。 描述> 如果分箱边界有重复(导致区间数量少于指定的 q 值),'raise' 会抛出异常,'drop' 会删除重复的边界。默认为 'raise'。Function description
- Return Value: returns a Series of Categorical type, with each value corresponding to the quantile group it belongs to.
- effect: maps continuous values to discrete categories by quantile, with each category containing roughly the same number of samples.
Example
Let us thoroughly master pd.qcut() through a series of examples from simple to complex.
Example 1: basic usage - binning by quartiles
Example
import numpy as np
# 1. Create skewed numeric data (most values are small)
np.random.seed(42)
data = np.random.exponential(scale=2, size=100) # exponentially distributed data
# take a subset for readability
scores = pd.Series(data[:20])
print("=== Original data ===")
print(scores.sort_values().values)
# 2. Use pd.qcut() to split the data into 4 quantile groups (quartiles)
result = pd.qcut(scores, q=4)
print("\n=== pd.qcut(scores, q=4) quartile binning ===")
print(result.value_counts().sort_index())
Expected output:
=== 原始数据 === [ 0.078 0.29 0.68 0.91 1.03 1.06 1.23 1.3 1.5 1.69 1.86 2.01 2.12 2.3 2.32 2.42 3.03 3.39 5.29 7.39]=== pd.qcut(scores, q=4) 四分位分箱 === (0.0783, 1.547] 5 (1.547, 2.315] 5 (2.315, 3.151] 5 (3.151, 7.393] 5 dtype: int64
Code analysis:
- For exponentially distributed data, using equal-width bins would concentrate most of the data in a single bin.
pd.qcut()ensures roughly the same number of samples in each bin (5 here, exactly 20/4).- The quantile cut points are computed from the actual data distribution rather than being evenly spaced.
Example 2: specifying custom quantiles
can be used via q The parameter lets you specify arbitrary quantiles, such as deciles or percentiles.
Example
import numpy as np
# 1. Create data
df = pd.DataFrame({
'name': ['Student_' + str(i) for i in range(1, 11)],
'score': [65, 78, 82, 55, 90, 72, 68, 85, 45, 95]
})
print("=== student score data ===")
print(df)
# 2. Bin by custom quantiles [0, 0.3, 0.7, 1.0], representing 30%, 70%, and 100%
result = pd.qcut(df['score'], q=[0, 0.3, 0.7, 1.0])
print("\n=== binning by the 30% and 70% quantiles ===")
print(result)
# 3. Add custom labels
labels = ['Pass', 'Good', 'Excellent']
result_labeled = pd.qcut(df['score'], q=3, labels=labels)
print("\n=== add custom labels ===")
print(result_labeled)
Expected output:
=== 学生成绩数据 ===
name score
0 Student_1 65
1 Student_2 78
2 Student_3 82
3 Student_4 55
4 Student_5 90
5 Student_6 72
6 Student_7 68
7 Student_8 85
8 Student_9 45
9 Student_10 95
=== 按 30% 和 70% 分位数分箱 ===
0 (44.999, 65.8]
1 (65.8, 86.4]
2 (65.8, 86.4]
3 (44.999, 65.8]
4 (86.4, 95.0]
5 (65.8, 86. 86.4]
6 (0.0, 44.999]
7 (44.999, 65.8]
8 (0.0, 44.999]
9 (65.8, 86.4]
10 (65.8, 86.4]
Code analysis:
q=[0, 0.3, 0.7, 1.0]Three intervals are defined: 0-30% (low score), 30%-70% (medium), and 70%-100% (high score).- Use
labelsThe parameter lets you name each interval instead of using the default interval notation.
Example 3: cut vs. qcut comparison
The comparison gives a clearer understanding of cut and qcut difference.
Example
import numpy as np
# 1. Create skewed data (most values are small)
data = pd.Series([1, 1, 1, 1, 1, 1, 1, 1, 1, 10, 20, 30, 40, 50])
print("=== Original data ===")
print(data.values)
# 2. Equal-width binning (pd.cut)
print("\n=== pd.cut equal-width binning ===")
cut_result = pd.cut(data, bins=4)
print(cut_result.value_counts().sort_index())
# 3. Equal-count binning (pd.qcut)
print("\n=== pd.qcut equal-count binning ===")
qcut_result = pd.qcut(data, q=4)
print(qcut_result.value_counts().sort_index())
Expected output:
=== 原始数据 === [ 1 1 1 1 1 1 1 1 1 10 20 30 40 50]=== pd.cut 等宽分箱 === (0.975, 13.25] 10 # 10 个值在这个区间 (13.25, 25.5] 1 (25.5, 37.75] 1 (37.75, 50.0] 2 # 2 个值在这个区间 dtype: 50
=== pd.qcut 等量分箱 === (0.999, 7.75] 4 # 约 1/4 的数据 (7.75, 25.0] 4 (25.0, 42.5] 4 (10.0, 50.0] 4 # 约 1/4 的数据
Code analysis:
pd.cut()divides the data range into 4 equal parts, but because the data is highly skewed, most values (nine 1s) fall in the first interval.pd.qcut()ensures each interval contains the same number of data points (4), even if the interval widths differ greatly.
Tip:
pd.cut()is suitable when the data is uniformly distributed or fixed-width intervals are needed.pd.qcut()is suitable when the data is unevenly distributed or needs to be split by rank/percentage.
Common Pandas functions