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

如何用单行代码创建带pd.CategoricalIndex的pd.Series

单行实现带CategoricalIndex的指定名称Series

情况1:从头构建目标Series

直接在pd.Series构造函数中完成所有配置,无需借助DataFrame中转:

pd.Series(data=[15, 25, 35], index=pd.CategoricalIndex(['2022Q1', '2022Q2', '2022Q3'], name='TIME_PERIOD'), name='OBS_VALUE')
  • data:传入序列的实际数值
  • index:直接传入pd.CategoricalIndex实例,同时通过其name参数设置索引名为TIME_PERIOD
  • name:指定Series本身的名称为OBS_VALUE

情况2:基于已有普通Series转换

如果已有一个普通Series,可通过链式调用单行完成转换:

original_series.rename('OBS_VALUE').set_axis(pd.CategoricalIndex(original_series.index, name='TIME_PERIOD'), axis=0)
  • rename('OBS_VALUE'):设置Series的名称
  • set_axis(...):将原索引替换为带名称的CategoricalIndex

内容的提问来源于stack exchange,提问作者Andrei.Danciuc

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 11:14:54