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

Python删除DataFrame多列异常:仅删除一列的解决建议咨询

Troubleshooting: Only One Column Deleted When Trying to Remove 800+ Columns from a Pandas DataFrame

Hey there! Let's dig into why only one column got deleted instead of the ~800 you targeted. Here are the most common culprits and fixes to get this sorted:

1. You're not modifying the DataFrame correctly in loops

If you wrote code like this to delete columns one by one:

for col in cols_to_drop:
    df.drop(col, axis=1)

This won't work! By default, drop() returns a new copy of the DataFrame instead of modifying the original. You have two options to fix this:

  • Assign the result back to your DataFrame every time:
    for col in cols_to_drop:
        df = df.drop(col, axis=1)
    
  • Use the inplace=True parameter (note: this modifies the DataFrame directly and is less recommended in newer pandas versions):
    for col in cols_to_drop:
        df.drop(col, axis=1, inplace=True)
    

That said, looping to delete 800 columns is inefficient—skip to point 4 for a better approach.

2. Most columns in your cols_to_drop list don't exist in the DataFrame

It’s possible that only one column name in your list actually matches a column in your DataFrame. To verify this, check how many of your target columns are present:

existing_cols = [col for col in cols_to_drop if col in df.columns]
print(f"Number of columns that exist in the DataFrame: {len(existing_cols)}")

If this number is 1, that’s exactly why only one column got deleted. You’ll need to fix your cols_to_drop list to ensure the column names match exactly (case-sensitive, no typos!).

3. You mixed up the axis parameter

Double-check that you’re using axis=1 in your drop() call. axis=0 targets rows, not columns. If you accidentally used axis=0, you might have deleted a row instead—but if you’re seeing a column missing, this is less likely, but worth ruling out.

The best way to delete multiple columns is to pass the entire list to drop() in a single call. This is way faster and avoids loop-related mistakes:

# Delete columns, ignoring any that don't exist (avoids errors)
df = df.drop(cols_to_drop, axis=1, errors='ignore')

# If you want to know which columns weren't deleted (no ignore)
try:
    df = df.drop(cols_to_drop, axis=1)
except KeyError as e:
    print(f"Columns not found: {e}")

Start by verifying your cols_to_drop list matches the DataFrame’s column names, then use the single-call method—it’ll save you time and headaches!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 06:22:44