Skip to main content
 首页 » 编程设计

python之Pandas cut 方法为值生成了错误的类别

2025年05月04日15jillzhang

我有以下数据框。

d = {'id': [1, 2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20], 'score': [23.4, 10.1,30.3,31.4,27.4,15.4,47.2,45.7,35.9,12.4,50.7,26.9,10.5,8.3,26.7,63.2,2.3,28.7,36.3,11.4]} 
df = pd.DataFrame(data=d) 
 
id  score 
1   23.4 
2   10.1 
3   30.3 
4   31.4 
5   27.4 
6   15.4 
7   47.2 
8   45.7 
9   35.9 
10  12.4 
11  50.7 
12  26.9 
13  10.5 
14  8.3 
15  26.7 
16  63.2 
17  2.3 
18  28.7 
19  36.3 
20  11.4 

我正在创建范围为 25 的类别。

score_range= ["[{0} - {1})".format(r, r + 25) for r in range(0, 100, 25)] 
score_range 
['[0 - 25)', '[25 - 50)', '[50 - 75)', '[75 - 100)'] 

我根据范围对“score”列的值进行了分类,得到了以下输出:

df['score_range'] = pd.cut(x=df['score'], bins=len(score_range), labels=score_range) 
df 
id  score   score_range 
1   23.4    [25 - 50) 
2   10.1    [0 - 25) 
3   30.3    [25 - 50) 
4   31.4    [25 - 50) 
5   27.4    [25 - 50) 
6   15.4    [0 - 25) 
7   47.2    [50 - 75) 
8   45.7    [50 - 75) 
9   35.9    [50 - 75) 
10  12.4    [0 - 25) 
11  50.7    [75 - 100) 
12  26.9    [25 - 50) 
13  10.5    [0 - 25) 
14  8.3 [0 - 25) 
15  26.7    [25 - 50) 
16  63.2    [75 - 100) 
17  2.3 [0 - 25) 
18  28.7    [25 - 50) 
19  36.3    [50 - 75) 
20  11.4    [0 - 25) 

'score'值47.2、45.7、35.9、36.3落在[50-75]范围内,63.2、50.7落在[75-100]范围内,不应该。

47.2、45.7、35.9、36.3应该在[25-50]范围内,63.2、50.7应该在[50-75]范围内!

为什么 Pandas.cut 方法会生成错误的类别?

请您参考如下方法:

类别错误,因为您将不正确的参数传递给 bins。就目前而言,您将一个整数传递给 bins,因此行为是:

int : Defines the number of equal-width bins in the range of x.

您需要向它传递一个标量序列:

df['score_range'] = pd.cut(x=df['score'], bins=range(0, 125, 25), right=False) 
 
    id  score score_range 
0    1   23.4     [0, 25) 
1    2   10.1     [0, 25) 
2    3   30.3    [25, 50) 
3    4   31.4    [25, 50) 
4    5   27.4    [25, 50) 
5    6   15.4     [0, 25) 
6    7   47.2    [25, 50) 
7    8   45.7    [25, 50) 
8    9   35.9    [25, 50) 
9   10   12.4     [0, 25) 
10  11   50.7    [50, 75) 
...