首页 > 解决方案 > Pandas pd.cut ValueError:值的长度与索引的长度不匹配

问题描述

我有一个具有相同行数的数据框和系列。

的结果pd.cut也输出具有相同形状的数据。

我哪里错了?

我的数据框,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

我哪里错了?

标签: pythonpandas

解决方案


retbins=Truepd.cut()你返回一个元组。(请参阅文档。)

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

应该管用


推荐阅读