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

如何向pandas Categorical子集追加最后一个类别?

解决Categorical对象无法使用append追加元素的问题

我明白你的需求:先提取每隔4个的分类子集,再把最后一个分类追加进去,但遇到了'Categorical' object has no attribute append的报错——这很正常,因为pandas的Categorical类型确实没有内置的append方法,我们可以用下面两种方式来实现你的需求:

方法一:转成列表操作后转回Categorical

先把Categorical对象转换成普通列表,完成追加操作后再转回Categorical,还可以保留原分类的属性:

import pandas as pd
import numpy as np

# 你的原始代码
a = np.arange(0, 10, 1)
b = np.arange(0, 10, 1)
c = pd.cut(x = b.tolist(), bins = a, right = True, include_lowest = True)

# 提取子集
sub_c = c[0::4]

# 转列表追加最后一个分类,再转回Categorical(保留原分类的结构)
sub_c_list = sub_c.tolist()
sub_c_list.append(c[-1])
new_sub_c = pd.Categorical(sub_c_list, categories=c.categories, ordered=c.ordered)

方法二:用pd.concat拼接Categorical

把要追加的单个分类包装成一个新的Categorical对象,再用pd.concat拼接两个Categorical:

# 提取子集
sub_c = c[0::4]

# 创建包含最后一个分类的单元素Categorical
last_category = pd.Categorical([c[-1]], categories=c.categories, ordered=c.ordered)

# 拼接得到新的Categorical
new_sub_c = pd.concat([sub_c, last_category])

这两种方法都能实现你想要的效果,而且都会保留原Categorical的分类顺序、区间定义等属性,不会出现分类错乱的问题。

内容的提问来源于stack exchange,提问作者user3389288

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:36:02