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

Python 3.6.3中含NaN/-NaN的行无法用df.dropna删除,求解决

Why df.dropna() Isn't Removing Rows With "nan" or "-nan"

Ah, I’ve hit this exact snag before—let me break down what’s going on here.

The core issue is that your "nan" and "-nan" values are string literals, not the actual missing value types that pandas recognizes. The dropna() method only targets genuine missing values like:

  • numpy.nan
  • pandas.NA
  • Python's None

When pandas sees a string like "nan", it treats it as a regular non-missing value—so dropna() ignores those rows entirely.

How to Fix This

First, convert those string "nan"/"-nan" entries to proper missing values, then run dropna():

  1. Replace string literals with np.nan
    Use the replace() method to swap the problematic strings:

    import numpy as np
    df = df.replace(['nan', '-nan'], np.nan)
    

    Alternatively, use mask() to target any cell matching those strings:

    df = df.mask(df.isin(['nan', '-nan']))
    
  2. Drop the now-recognized missing values
    Now dropna() will work as expected:

    df = df.dropna(axis=0, how="any")
    

How to Verify the Fix

To confirm the strings are gone and replaced with real NaNs, you can run:

  • df.isna().sum(): This will show the count of missing values per column (should now include your former "nan" entries)
  • df.applymap(type): Checks the data type of every cell—your converted values should show as float (since np.nan is a float type)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 06:23:13