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

求助:使用df.drop无法删除Pandas DataFrame指定行的问题

解决Pandas遍历DataFrame时无法删除指定行的问题

问题核心原因

  1. 删除代码错误:你使用的df1.drop(df1.index,inplace=True)会删除整个DataFrame的所有行,而非当前遍历的目标行,正确删除当前行需要指定对应索引df1.drop(index, inplace=True)。
  2. 遍历与修改冲突:直接在iterrows()遍历原DataFrame时删除行,会导致后续遍历的索引错位——因为删除行后DataFrame的索引会动态变化,可能出现跳过或重复处理行的情况。

修正方案

方案一:收集待删除索引,批量处理(推荐)

先遍历标记需要删除的行索引,遍历完成后一次性删除,避免动态修改DataFrame带来的索引问题,性能也更优:

import pandas as pd

df1 = pd.read_csv('questions.csv', usecols=['question_id','question'])
to_delete = []

for index, row in df1.iterrows():
    print(row['question'])
    Check1 = input("Is the following question correct? (Y/N): ")
    if Check1 == "Y":
        continue
    elif Check1 == "N":
        Check2 = input("Is this question Needed? (Y/N) ")
        if Check2 == "N":
            Check3 = input("Are you sure you want to Delete this question? (Y/N) ")
            if Check3 == "Y":
                to_delete.append(index)
        elif Check2 == "Y":
            Check4 = input("Please rewrite the question: ")
            df1.loc[index, 'question'] = Check4

# 批量删除标记的行
df1.drop(to_delete, inplace=True)
# 保存修改后的结果到新文件
df1.to_csv('questions_updated.csv', index=False)

方案二:遍历索引副本,逐行删除

如果需要实时删除行,可遍历原DataFrame索引的副本,避免原索引变化影响遍历流程:

import pandas as pd

df1 = pd.read_csv('questions.csv', usecols=['question_id','question'])

# 遍历索引副本,防止删除行后索引错位
for index in df1.index.copy():
    row = df1.loc[index]
    print(row['question'])
    Check1 = input("Is the following question correct? (Y/N): ")
    if Check1 == "Y":
        continue
    elif Check1 == "N":
        Check2 = input("Is this question Needed? (Y/N) ")
        if Check2 == "N":
            Check3 = input("Are you sure you want to Delete this question? (Y/N) ")
            if Check3 == "Y":
                df1.drop(index, inplace=True)
        elif Check2 == "Y":
            Check4 = input("Please rewrite the question: ")
            df1.loc[index, 'question'] = Check4

# 保存修改后的结果
df1.to_csv('questions_updated.csv', index=False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 19:05:48