熊猫切割方法为值生成错误的类别

时间:2019-07-15 14:15:37

标签: python pandas dataframe categories

我有以下数据框。

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)']

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

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)

“得分”值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方法生成错误的类别?

2 个答案:

答案 0 :(得分:4)

类别错误,因为您将错误的参数传递给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)
...

答案 1 :(得分:3)

为什么不使用没有自己创建的标签的pd.cut,同样在创建垃圾箱时,您可能需要为上边界添加一个垃圾箱大小

pd.cut(df.score, range(0, 125, 25))