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

如何删除DataFrame中指定列以外的所有列?

解决Pandas保留指定列、删除其余列的问题

你的写法df = df.drop(columns != ['Plant', 'Date', 'Type'])语法不成立,因为columns != ['Plant', 'Date', 'Type']不是合法的参数形式。下面是几种可行的实现方式:

方法1:直接索引指定列(最简洁)

直接通过列名列表选取需要保留的列,这是日常最常用的方式:

df = df[['Plant', 'Date', 'Type']]

如果不确定目标列是否都存在于DataFrame中,可以加个判断避免报错:

keep_cols = ['Plant', 'Date', 'Type']
df = df[[col for col in keep_cols if col in df.columns]]

方法2:用drop()配合列名差集

先计算需要删除的列(所有列减去要保留的列),再传给drop()的columns参数:

keep_cols = ['Plant', 'Date', 'Type']
drop_cols = [col for col in df.columns if col not in keep_cols]
df = df.drop(columns=drop_cols)

方法3:用reindex()指定保留列

这种方式会自动过滤不存在的列,同时可以自定义列的展示顺序:

df = df.reindex(columns=['Plant', 'Date', 'Type'])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 09:50:34