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

按数据类型筛选列并保留指定列时触发IndexError的问题求助

按数据类型筛选列并保留指定列时触发IndexError的问题求助

我现在需要实现一个需求:从DataFrame里筛选出所有object类型的列,同时还要额外保留Number和Age这两个指定列。

我先用一个示例数据集做测试(实际工作中我的数据集有450多列,列数很多),示例代码如下:

import pandas as pd
# 读取示例数据集
data = pd.read_csv("nba.csv")
data.head()

# 提取所有object数据类型的列
object_cols = data.select_dtypes(include='object')

之后我尝试把指定的Number、Age列和筛选出来的object类型列合并成新的DataFrame,写了这段代码:

RequiredDataframe1 = data[data.columns["Number", "Age", object_cols.columns.values]]

结果直接触发了IndexError,报错信息如下:

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

有没有大佬能帮忙看看这段代码哪里出问题了?应该怎么正确实现我想要的需求呀?

备注:内容来源于stack exchange,提问作者JK1185

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 14:42:58