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

Python 3中无法为已索引DataFrame添加年度总计列求助

解决Flights数据集多层索引DataFrame添加年度总计列的CategoricalIndex错误

嘿,我之前也踩过这个坑!你遇到的cannot insert an item into a CategoricalIndex that is not already an existing category错误,核心原因是seaborn加载的flights数据集中,month列是分类(Categorical)类型。当你执行unstack()后,列索引的month层级变成了CategoricalIndex,而这类索引要求所有新增的列名必须是已定义的分类值——显然total不在原来的12个月份分类里,所以直接赋值或插入都会报错。

下面给你两种可行的解决方案,按需选择:

方案一:将month转为普通字符串索引(简单直接)

如果不需要保留month的分类属性,先把它转成字符串类型,后续操作就和普通多层索引DataFrame一样顺畅:

import pandas as pd
import seaborn

flights = seaborn.load_dataset('flights')
# 把month从分类类型转为字符串,消除CategoricalIndex限制
flights['month'] = flights['month'].astype(str)
flights_indexed = flights.set_index(['year','month'])
flights_unstacked = flights_indexed.unstack()

# 添加年度总计列
flights_unstacked['passengers', 'total'] = flights_unstacked.sum(axis=1)

# 如果想把total列放在最前面,可以用reindex调整列顺序
flights_unstacked['passengers'] = flights_unstacked['passengers'].reindex(
    columns=['total'] + flights_unstacked['passengers'].columns.tolist()
)

方案二:保留分类类型,先新增分类值

如果需要保留month的分类特性,先给CategoricalIndex添加total这个新类别,再进行赋值操作:

import pandas as pd
import seaborn

flights = seaborn.load_dataset('flights')
flights_indexed = flights.set_index(['year','month'])
flights_unstacked = flights_indexed.unstack()

# 给month层级的分类索引新增'total'类别
flights_unstacked.columns = flights_unstacked.columns.set_levels(
    flights_unstacked.columns.levels[1].add_categories('total'),
    level=1
)

# 现在可以正常添加总计列了
flights_unstacked['passengers', 'total'] = flights_unstacked.sum(axis=1)

两种方案都能解决你的问题,方案一更适合快速实现需求,方案二则保留了数据的分类结构,方便后续的分类相关操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:10:41