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

如何向pandas.core.indexes.base.Index对象追加指定列名

你运行代码报错的核心原因是:new_thing本身是pandas的Index类型,调用它的append方法时必须传入同样是Index类型的参数,你之前传的df.target是target列的整列数据(Series类型),不符合参数要求,所以触发了TypeError。

以下是几种可行的实现方式:

  • 方式1:直接使用Index的append方法,传入包裹了target列名的Index对象
new_thing = new_thing.append(pd.Index(['target']))
  • 方式2:把Index转成列表拼接后再转回Index,可读性更高
new_thing = pd.Index(new_thing.tolist() + ['target'])
  • 方式3:调用insert方法在指定位置插入列名,比如下面的代码会把target插到列名列表的最后
new_thing = new_thing.insert(len(new_thing), 'target')

运行上述任意一种代码后,打印new_thing就能看到已经包含了target列,输出为:

Index(['cot1', 'cat3', 'target'], dtype='object')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 10:36:01