pd.to_numeric converts values into numeric data. With errors='coerce', it replaces unconvertible values with NaN instead of raising an exception. section 5.6
Clean an age column
Convert celebrity-death ages with df['age'] = pd.to_numeric(df['age'], errors='coerce'), inspect the result with describe(), then retain plausible ages using df.loc[df['age'] < 120]. This catches both nonnumeric entries and values such as 9394 that convert successfully but remain implausible. section 5.6
df['age'] = pd.to_numeric(df['age'], errors='coerce')
Use the concise coercion pattern for converting a pandas column while marking failed conversions as missing. section 5.6
A practical cleanup sequence is:
- Convert the column with pd.to_numeric. section 5.6
- Inspect descriptive statistics to find suspicious converted values. section 5.6
- Filter the cleaned data using a domain-specific threshold. section 5.6
