首页 > 解决方案 > 熊猫有条件地在for循环中删除行

问题描述

我的 Pandas DataFrame 有 17543 行。我想删除一行,前提是每列都包含“nan”。我按照for 循环中的链接删除行尝试了说明, 但没有帮助。以下是我的代码

NullRows=0
for i in range(len(SetMerge.index)):
    if(SetMerge.iloc[i].isnull().all()):
        df=SetMerge.drop(SetMerge.index[i])
        NullRows +=1

print("total null rows : ", NullRows)

我只在 df 中删除了一行,有 17542 行,而 NullRows 输出为 30。

标签: pythonpandasfor-loop

解决方案


drop不会改变你的SetMerge. SetMerge因此,您需要在之后重新分配drop,或使用其他功能。它是通过您在此处发布并检查的链接写在答案中的。为突变指定 inplace=True 选项。


推荐阅读