0

我有一列的值从 0 变为 600,我想将该值从 0 到 9.2 以 0.4 的增量分组,并将 1 组在 9.2 和 600 之间的值作为异常值。我尝试了以下代码;

bin_labels = ['0-0.4', '0.4-0.8', '0.8-1.2', '1.2-1.6',
          '1.6-2.0', '2.0-2.4','2.4-2.8', '2.8-3.2',
          '3.2-3.6', '3.6-4.0','4.0-4.4', '4.4-4.8',
          '4.8-5.2', '5.2-5.6','5.6-6.0', '6.0-6.4',
          '6.4-6.8', '6.8-7.2','7.2-7.6', '7.6-8.0',
          '8.0-8.4', '8.4-8.8','8.8-9.2']

bins = np.linspace(0.0,9.2,24)

df['A_group'] = pd.cut(df['A'], bins = bins, labels = bin_labels, include_lowest = True)

之后,我想使用以下代码用“9.2-more”标签值填充 9.2 到 600 之间的值;

df['A_group'] = df['A_group'].fillna('9.2-more')   

但它说以下错误;

无法在具有新类别的分类上设置项目,请先设置类别

4

1 回答 1

1

您可以附加float("inf")bins并在以下内容中包含“9.2-more” bin_labels

bin_labels = [  '0-0.4', '0.4-0.8', '0.8-1.2', '1.2-1.6',
              '1.6-2.0', '2.0-2.4', '2.4-2.8', '2.8-3.2',
              '3.2-3.6', '3.6-4.0', '4.0-4.4', '4.4-4.8',
              '4.8-5.2', '5.2-5.6', '5.6-6.0', '6.0-6.4',
              '6.4-6.8', '6.8-7.2', '7.2-7.6', '7.6-8.0',
              '8.0-8.4', '8.4-8.8', '8.8-9.2', "9.20-more"]

bins = np.append(np.linspace(0.0, 9.2, 24), float("inf"))
df["A_group"] = pd.cut(df['A'], bins = bins, labels = bin_labels, include_lowest = True)
于 2021-11-05T14:05:36.593 回答