如何向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
相关产品推荐
相关产品推荐

