skip to content

After upgrading a loan-scoring script to pandas 3.0, `df.applymap(fmt)` raises AttributeError; how do you migrate the call safely?

level: middleimportance: should knowfreq 44%

answer

  1. a name that changed in 3.0
  2. the elementwise call now matches Series.map
  3. missing cells can be skipped
  4. the styler has the same rename

basics

~10 s

pandas 3.0 removed DataFrame.applymap; rename it to DataFrame.map, which calls the function on every cell. Add na_action="ignore" if the function cannot take NaN, and prefer a vectorized method where one exists.

solid answer

~30 s

`DataFrame.applymap` was deprecated in 2.1 and is removed in pandas 3.0, together with `Styler.applymap` and `Styler.applymap_index`, so the call raises `AttributeError`. The replacement is `df.map(fmt)`: the same cell-by-cell call, returning a frame of the same shape. It is not `df.apply(fmt)`, which hands the function whole columns. Two arguments carry over: `na_action="ignore"` leaves missing cells alone instead of passing NaN to `fmt`, and extra keywords are forwarded, as in `df.map(round, ndigits=2)`. In reporting code the styler calls become `Styler.map` and `Styler.map_index`. Since `map` is still one Python call per cell, I also check whether `df.round` or a `.str` method can replace it.

code

python · 13 lines
python
import numpy as np
import pandas as pd

loans = pd.DataFrame({
    "income": [52000.0, np.nan, 61000.0],
    "debt": [9000.0, 4000.0, 12000.0],
})
fmt = lambda v: f"{v:,.0f}"

print(hasattr(loans, "applymap"))           # False in pandas 3.0
print(loans.map(fmt))                       # NaN becomes the text "nan"
print(loans.map(fmt, na_action="ignore"))   # NaN stays missing
print(loans.round(-3))                      # vectorized, no per-cell call

go deeper

for a junior

Recall that pandas 3.0 removed applymap and that DataFrame.map is the cell-by-cell replacement.

for a middle

Explain how DataFrame.map, DataFrame.apply and Series.map differ in what each call receives, and when na_action="ignore" is needed.

for a senior

Show how you would find every applymap call, styler code included, before the upgrade, and where you would replace per-cell work with a vectorized method.

for a principal

Plan the 3.0 upgrade around warnings first: run 2.x with deprecation warnings as errors, fix renames in one sweep, and refuse compatibility shims.

## What pandas 3.0 removed The pandas 3.0 release notes list one removal for this call: **`DataFrame.applymap`, `Styler.applymap` and `Styler.applymap_index` are gone**. All three were deprecated in pandas 2.1, when the replacements arrived under names that match `Series.map`: | Removed in 3.0 | Use instead | Added in | |---|---|---| | `DataFrame.applymap(func)` | `DataFrame.map(func)` | 2.1 | | `Styler.applymap(func)` | `Styler.map(func)` | 2.1 | | `Styler.applymap_index(func)` | `Styler.map_index(func)` | 2.1 | On pandas 3.0, the old call fails at attribute lookup: `AttributeError: 'DataFrame' object has no attribute 'applymap'`. Nothing was renamed in behaviour, only in name, so the migration is mechanical. ## What `DataFrame.map` does `DataFrame.map(func, na_action=None, **kwargs)` calls `func` once for **every cell** and returns a new DataFrame of the same shape, with the same index and columns. It is easy to confuse with its neighbours, because each one hands the function something different: | Call | Granularity | `func` receives | Typical use | |---|---|---|---| | `DataFrame.map(func)` | each cell | a scalar | formatting or cleaning every value | | `DataFrame.apply(func)` | each column (`axis=0`) | a Series | a per-column calculation | | `DataFrame.apply(func, axis=1)` | each row | a Series | a per-row rule | | `Series.map(func_or_dict)` | each value of one column | a scalar or a lookup key | recoding one column | Swapping `applymap` for `apply` is the common wrong fix: the function then receives whole columns, and a formatter written for one number either raises or formats a Series. ## Two arguments that carry over 1. **`na_action="ignore"`** leaves missing cells as they are instead of passing NaN to the function. With the default `None`, a formatter such as `lambda v: f"{v:,.0f}"` turns NaN into the text `"nan"`, and a converter such as `int` raises `ValueError: cannot convert float NaN to integer`. If the old `applymap` call relied on clean input, add `na_action="ignore"` when you rename it. 2. **Extra keyword arguments** are forwarded to the function, so `df.map(round, ndigits=2)` works without a lambda. ## Rename, then ask whether `map` is needed at all `DataFrame.map` is still one Python call per cell, so on a large frame it is slow. The upgrade is a good moment to check whether a vectorized method already does the job: - rounding: `df.round(2)` instead of `df.map(round, ndigits=2)` - text cleanup on a string column: `df["name"].str.strip()` instead of a per-cell `strip` - type conversion: `df.astype("float64")` or `pd.to_numeric(df[col], errors="coerce")` Keep `map` where the logic really is per value and no built-in covers it, such as display formatting. ## A migration checklist - Search the codebase for `applymap(`, including `.style.applymap(` and `.style.applymap_index(` in reporting code, and rename each call to `map` or `map_index`. - Where the old function assumed non-missing input, add `na_action="ignore"`. - Before the upgrade, run the test suite on pandas 2.1 or later with deprecation warnings turned into errors: the old names warn there and point to the replacement, which catches tested paths before 3.0 removes them. - Replace per-cell numeric work with a vectorized method where one exists.

  • How would you find these calls before upgrading a 2.x codebase?
    Run the test suite on pandas 2.1 or later with deprecation warnings turned into errors, for example `pytest -W error::FutureWarning`. Each `applymap` call warns there and names `map` as the replacement. Then grep for `applymap(` to catch paths the tests do not reach, including styler calls in reporting code.
  • Why not keep the code working by adding applymap back as an alias?
    Monkey-patching `DataFrame.applymap = DataFrame.map` hides the removal from every reader and from the next upgrade, and it patches a library class globally. The rename is mechanical and searchable, so making it once is cheaper than carrying a shim that every new hire has to discover.

  • Says applymap still works on pandas 3.0 with a deprecation warning
  • Replaces applymap with DataFrame.apply, which passes whole columns
  • Believes DataFrame.map skips NaN cells by default
  • Assumes DataFrame.map is vectorized and as fast as df.round

Assumes pandas 3.0: DataFrame.applymap, Styler.applymap and Styler.applymap_index, deprecated in 2.1, are removed in favour of DataFrame.map, Styler.map and Styler.map_index.