首页 > 解决方案 > bin 标签必须比 bin 边缘的数量少一

问题描述

我遇到了与这个问题非常相似的错误,但答案对我不起作用。

我有一个包含许多数字列的数据框,我想为其创建 bin。我正在尝试通过一个简单的功能来做到这一点:

def bin_data(df, numerical_cols):
  cuts=4 #number of cuts to create
  for column in numerical_cols: #loop through each numerical column name
    print(column)
    unique_var = len(np.unique([i for i in df[column]]))
    labels1 = range(1, min(unique_var,cuts)+1) #dynamically generate labels based on unique_var
    print('unique value is', labels1)
    new_column_name = (column + "_bin")
    # labels1 = [1, 2, 3, 4]
    df[new_column_name] = pd.qcut(df[column], q=min(unique_var,cuts),
                                              # q=4,
                                              labels=labels1,
                                              precision=10,
                                              duplicates='drop')
    numerical_cols.append(new_column_name)
  return df, numerical_cols

如您所见,我向它发送了一个数据框,即数字列的列表。它遍历每个数字列并创建一个带有 bin 的新列 - 我想要 qbin 因为我希望分布或多或少是平衡的。

当我运行它时,我收到了这个错误:Bin labels must be one fewer than the number of bin edges我受到链接问题的启发来调整我的代码,但我仍然收到这个错误。有什么我可以做的吗?

标签: pythonpandas

解决方案


推荐阅读