You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用pd.cut分箱后fillna触发Categorical新类别报错如何解决

错误原因

pd.cut默认返回Categorical分类类型数据,该类型的取值只能是预先定义好的类别集合,你当前生成的A_group的类别只有你写的23个区间标签,不存在9.2-more,所以直接填充不存在的类别会触发报错。


解决方案1:直接在分箱阶段包含异常值组(更推荐)

直接把分箱边界扩展到600,同时提前把9.2-more加到标签列表里,一步生成结果:

import numpy as np
import pandas as pd

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.2-more']

# 分箱边界最后追加600即可
bins = np.append(np.linspace(0.0,9.2,24), 600)

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

解决方案2:先添加新类别再填充空值

如果要保留原有分箱代码,可以先给Categorical列新增9.2-more类别,再执行填充:

# 原有分箱代码不变
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)

# 先新增类别再填充空值
df['A_group'] = df['A_group'].cat.add_categories('9.2-more').fillna('9.2-more')

内容的提问来源于stack exchange,提问作者Ugur Selim Ozen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 02:36:03