Pandas pd.cut ValueError:值的长度与索引的长度不匹配



我有一个具有相同行数的数据帧和序列。

CCD_ 1的结果也输出具有相同形状的数据。

我哪里错了?

我的数据帧,37459行:

df.shape
(37459, 124)

我试图剪切的列,37459行:

df['score']
2        74.390244
4        29.268293
5        45.121951
6        46.341463
7        31.707317
...    
43502    21.951220
43503     1.219512
43505     3.658537
43506     8.536585
43507    12.195122
Name: score, Length: 37459, dtype: float64

以及pd.cut的输出:

pd.cut(df['score'], [0, 33, 66, 100], labels=[1,2,3], retbins=True, right=False)
(2        3
4        1
5        2
6        2
7        1
..
43502    1
43503    1
43505    1
43506    1
43507    1
Name: score, Length: 37459, dtype: category
Categories (3, int64): [1 < 2 < 3], array([  0,  33,  66, 100]))

我试图将pd.cut的结果附加到df。我试图将其分成三组,并将其标记为[1,2,3]:

df['score_cut'] = pd.cut(df['score'], [0, 33, 66, 100], labels=[1,2,3], retbins=True, right=False)

ValueError: Length of values does not match length of index

我哪里错了?

retbins=True使pd.cut()返回一个元组。(见文档(

df['score_cut'], bins = pd.cut(df['score'], [0, 33, 66, 100], labels=[1,2,3], retbins=True, right=False)

应该工作

你试过qcut吗?

pd.qcut(df['score'], [0, .33, .66, 1], labels=[1,2,3], retbins=True, right=False)

因为df['score_cut']的这个形状不等于右边。