【问题标题】:Cutting continous variable into catagories ( ValueError: Bin labels must be one fewer than the number of bin edges)将连续变量划分为类别(ValueError:Bin 标签必须比 bin 边缘的数量少一)
【发布时间】:2021-08-26 12:34:01
【问题描述】:

我有一个数据列,我想将其分割成离散的 bin。我的min 是 1,max 是 70

df.total_value.describe()
count       37926.000000
mean        12.368138
std          7.385642
min          1.000000
25%          8.000000
50%         10.000000
75%         16.000000
max         70.000000
Name: total_value, dtype: float64

我试过了

labels = ["{0} - {1}".format(i, i + 1) for i in range(1, 70, 1)]

cut_bins = range(1, 70)
df['total_value_bins'] = pd.cut(df['total_value'], bins= cut_bins, labels=labels)

我收到此错误

ValueError: Bin labels must be one fewer than the number of bin edges

如果我使用,我能够得到垃圾箱

df['total_value_bins'] = pd.cut(df['total_value'], bins= cut_bins)

但我想要很好地格式化e.g. 1-2

任何建议帮助将不胜感激。

提前致谢。

【问题讨论】:

    标签: python pandas cut data-wrangling


    【解决方案1】:

    正如错误所说,您需要拥有len(cut_bins) = len(labels)+1,而现在它们的长度相同。此外,为了能够合并值 1 和 70,您需要将 cut_binsrange 中的上限更改为 71(因为上限未在 range 中创建),并使用参数include_lowest in cut

    labels = ["{0} - {1}".format(i, i + 1) for i in range(1, 70, 1)]
    
    cut_bins = range(1, 71) # here goes to 71
    
    # dummy data
    s = pd.Series([1,4,45,70])
    
    print(pd.cut(s, bins= cut_bins, labels=labels, include_lowest=True))
    0      1 - 2
    1      3 - 4
    2    44 - 45
    3    69 - 70
    dtype: category
    Categories (69, object): ['1 - 2' < '2 - 3' < '3 - 4' < '4 - 5' ... '66 - 67' < '67 - 68' < '68 - 69' < '69 - 70']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-26
      • 2017-11-22
      • 1970-01-01
      • 1970-01-01
      • 2019-11-24
      • 1970-01-01
      相关资源
      最近更新 更多