Python 3.6.3中含NaN/-NaN的行无法用df.dropna删除,求解决
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.nanpandas.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():
Replace string literals with
np.nan
Use thereplace()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']))Drop the now-recognized missing values
Nowdropna()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 asfloat(sincenp.nanis a float type)
内容的提问来源于stack exchange,提问作者Francesca

