首页 > 解决方案 > Pandas cut 方法为值生成错误的类别

问题描述

我有以下数据框。

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 方法会生成错误的类别?

标签: pythonpandasdataframecategories

解决方案


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

int :定义x 范围内等宽 bin 的数量

你需要传递一个sequence of scalars

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)
...

推荐阅读