After upgrading to pandas 3.0, a cleaning step df.apply(pd.to_numeric, errors='ignore') raises ValueError, and it had been stripping leading zeros from ID codes — what do you replace it with?
answer
- a removed option, not a bug
- convert-if-it-parses hid two problems
- identifiers are text, not numbers
- name the numeric columns explicitly
basics
~20 sIn pandas 3.0, to_numeric no longer accepts errors='ignore', so the call raises. Replace the blanket conversion with an explicit list of numeric columns, coerce those with a NaN check, and keep ID codes as text.
solid answer
~40 sIn pandas 3.0, `pd.to_numeric` accepts only `errors='raise'` or `'coerce'`; `'ignore'`, deprecated in 2.2, now raises `ValueError: invalid error value specified`. The old idiom converted every column that parsed and silently left the rest, which is exactly why IDs like `'00721'` became `721`: they parse cleanly. Do not swap in `errors='coerce'` across the frame, which turns every text column into `NaN`. Instead name the numeric columns, run `pd.to_numeric(..., errors='coerce')` on those with a check on how many values became missing, and keep identifier columns as text, ideally declared at read time. Where you truly need convert-if-possible, write a small helper that catches `ValueError` per column.
code
python · 19 linesimport pandas as pd
df = pd.DataFrame({
"sku": ["00721", "00045"],
"qty": ["3", "4"],
"name": ["cap", "mug"],
})
try:
df.apply(pd.to_numeric, errors="ignore")
except ValueError as exc:
print("3.0:", exc)
print(df.apply(pd.to_numeric, errors="coerce")["name"].tolist())
NUMERIC = ["qty"]
out = df.copy()
out[NUMERIC] = out[NUMERIC].apply(pd.to_numeric, errors="coerce")
print(out["sku"].tolist(), out["qty"].dtype)go deeper
Recall that pandas 3.0 removed errors='ignore' from to_numeric, and that digit-only codes such as '00721' lose their leading zeros when parsed as numbers.
Explain what the old idiom did per column, and why errors='coerce' over the whole frame turns text columns into NaN instead of leaving them alone.
Replace the blanket conversion with an explicit schema: named numeric columns coerced with a missing-count check, identifiers kept as text, and a test that guards both.
Use the upgrade to require declared column types at pipeline boundaries, so convert-if-it-parses heuristics cannot reappear in new code.
## What changed in pandas 3.0 `pd.to_numeric(arg, errors='raise', downcast=None, dtype_backend=...)` used to accept three values for `errors`: `'raise'`, `'coerce'` and `'ignore'`. With `'ignore'`, a column that failed to parse was returned **unchanged**. pandas 2.2 deprecated that option for `to_numeric`, `to_datetime` and `to_timedelta`, recommending that callers "explicitly catch exceptions instead". **In pandas 3.0 it is removed**: the function validates `errors` against `('raise', 'coerce')` and otherwise raises `ValueError: invalid error value specified`. Because `DataFrame.apply` forwards extra keyword arguments to the function, `df.apply(pd.to_numeric, errors='ignore')` calls `to_numeric` once per column with that argument, and the first call raises. The whole cleaning step fails, not just one column. Note the asymmetry: `DataFrame.astype` still accepts `errors='ignore'` in 3.0. The removal is specific to the three parsing functions. ## Why the option went away The pandas 2.2 release notes give the replacement in one line: "explicitly catch exceptions instead". The point of that advice is visibility. With `errors='ignore'`, a failure and a success looked the same to the caller, because both returned a Series; only the dtype differed, and nobody checked it. A `try/except ValueError` written in your own code makes the failure branch a line you can read, log and test. That is also the shape of the replacement below. ## What the old idiom was really doing `df.apply(pd.to_numeric, errors='ignore')` was popular because it looked like "make numbers numeric and leave text alone". In practice it applied a **convert-if-every-value-parses** rule column by column, and that rule hid two problems: - **Identifiers that look like numbers were converted.** A SKU or postal code such as `'00721'` parses as the number `721`. The leading zeros are not part of any numeric value, so they are gone, and `astype(str)` later produces `'721'` (or `'721.0'` if the column had gaps and became `float64`). - **Numeric columns with one bad value stayed text, silently.** A price column with a single `'N/A'` failed to parse, so the whole column was returned as strings, and the job carried on. The 3.0 error is therefore an opportunity: the step was already wrong. ## Replacements that look right but are not | Replacement | What it does to the frame | |---|---| | `df.apply(pd.to_numeric, errors='coerce')` | every text column, such as product names, becomes all `NaN`, as `float64` | | `df.apply(pd.to_numeric)` | raises on the first column that does not parse | | `df.astype(float, errors='ignore')` | same blanket convert-if-possible rule, IDs still lose their zeros | | `df.convert_dtypes()` | does not parse text at all, so prices stay strings | ## The fix: name the columns 1. **Declare intent.** Write down which columns are numeric (`NUMERIC = ['price', 'qty']`) and which are identifiers (`IDS = ['sku']`). This is the schema the old idiom was guessing. 2. **Keep identifiers as text.** Ideally declare them as text when the file is read, which the lesson on CSV import covers; at minimum, never pass them to `to_numeric`. 3. **Convert numeric columns deliberately.** Strip formatting, then `pd.to_numeric(col, errors='coerce')`, and compare missing counts before and after so a format change cannot erase data silently. 4. **Fail loudly on surprises.** Use `errors='raise'` for columns that should already be clean. 5. **If you genuinely need convert-if-possible**, for exploratory work on an unknown file, write the behaviour explicitly and exclude identifiers: ```python import pandas as pd def to_numeric_if_clean(col: pd.Series) -> pd.Series: try: return pd.to_numeric(col) except ValueError: return col df = pd.DataFrame({"sku": ["00721", "00045"], "qty": ["3", "4"], "name": ["cap", "mug"]}) ids = ["sku"] others = df.columns.difference(ids) df[others] = df[others].apply(to_numeric_if_clean) ``` `sku` keeps its zeros, `qty` becomes `int64`, and `name` stays text. ## Repairing data already damaged - If the IDs have a known fixed width, `col.astype(str).str.zfill(5)` restores the zeros from an integer column. A `float64` column would stringify as `'721.0'`, so cast it to `'Int64'` first: `col.astype('Int64').astype(str).str.zfill(5)`. - If the width varies, the zeros cannot be reconstructed from the numbers; re-read the source with the column declared as text. - Add a test that asserts the identifier column's dtype and a sample value, so the next blanket conversion fails in CI rather than in a report. ## What an interviewer is checking That you recognise the error as a removed API, not a pandas bug; that you see the leading-zero loss and the silent text column as the same design flaw; and that your fix is an explicit schema rather than a different blanket option.
- Why does astype still accept errors='ignore' when to_numeric does not?The pandas 2.2 deprecation, and the 3.0 removal, covered only the parsing functions `to_numeric`, `to_datetime` and `to_timedelta`. `astype`'s signature in 3.0 still declares `errors: 'raise' | 'ignore'`, where `'ignore'` returns a failing column unchanged. It carries the same silent-failure risk, so the same advice applies: name the columns and check dtypes.
- How would you find which columns the old idiom had been converting?Apply a try/except `to_numeric` to each column of a representative sample and record which ones parse without error: the old option returned the input whenever parsing failed, so exactly those columns were being converted. Compare that list with the schema you intend. Any identifier on it, such as a SKU, postal code or account number, has been losing leading zeros.
- In pandas 3.0, errors='ignore' still works on to_numeric and only warns
- Switching to errors='coerce' is a drop-in replacement for errors='ignore'
- astype(str) after to_numeric restores the leading zeros
- The old idiom left identifier columns alone because they are text
- The ValueError is a pandas 3.0 bug to pin around by downgrading
pandas 2.2 deprecated errors='ignore' in to_numeric, to_datetime and to_timedelta; pandas 3.0 removed it, so passing it raises ValueError.