Sub topic 4
Missing values and na_action
This chapter assumes you can write Python functions and lambdas, build a pandas Series and DataFrame, and know that missing data in pandas is usually shown as NaN. It covers what your function receives when a value is missing, how na_action changes that for map, and how to write functions that handle missing data when na_action isn't available.
What "missing" looks like inside your function
pandas uses several markers for a missing value, and your function sees whichever one is stored in the data.
| Marker | Where it appears | Type seen by your function |
|---|---|---|
| `np.nan` | float columns, and object columns where it was inserted | `float` |
| `None` | object columns that keep it as given | `NoneType` |
| `pd.NA` | nullable dtypes such as `Int64`, `string`, `boolean` | `NAType` |
| `pd.NaT` | datetime and timedelta columns | `NaTType` |
pandas converts None to NaN when it builds a numeric column. pd.Series([1, None, 3]) has dtype float64. An object column can keep None as it is.
By default, map and apply call your function on every element, missing ones included. Your function is therefore the first code that decides what a missing value means. Some functions tolerate it and others don't:
- Arithmetic on
NaNgivesNaN, sox * 2quietly works. - Methods such as
str.upperraiseTypeError, becausefloatandNoneTypehave no such method. int(x)raisesValueErroronNaN.if x:raisesTypeErroronpd.NA, because its truth value is ambiguous.
The same function can run on one column and fail on another, depending on whether missing values are present.
The default: your function sees the missing value
Here is a string Series with one missing entry. Calling str.upper on it fails.
import numpy as np
import pandas as pd
s = pd.Series(["a", np.nan, "c"])
try:
s.map(str.upper)
except TypeError:
print("TypeError: str.upper was called on the missing value")map reached the second element, passed it to str.upper, and the call failed. No result Series is returned, even though two of the three values were fine.
Skipping missing values with na_action="ignore"
Series.map has a parameter na_action. The default is None, which passes everything to the function. With na_action="ignore", pandas finds the missing positions first and never calls your function on them. They are copied to the result unchanged.
import numpy as np
import pandas as pd
s = pd.Series(["a", np.nan, "c"])
print(s.map(str.upper, na_action="ignore"))0 A
1 NaN
2 C
dtype: objectThe function ran twice, not three times. The missing entry stays missing in the result, so the output keeps the same length and index as the input.
na_action also fixes the int failure on floats:
import numpy as np
import pandas as pd
s = pd.Series([1.0, np.nan, 3.0])
print(s.map(int, na_action="ignore"))0 1.0
1 NaN
2 3.0
dtype: float64The values are now whole numbers, but the dtype is still float64. A NumPy int64 column cannot hold NaN, so the result stays float as long as a missing value is present. If you need integers, convert to the nullable Int64 dtype afterwards with astype("Int64").
The next diagram shows how map decides what to do with each element.
Missing values when map receives a dict or Series
When map is given a dict, there is no function to fail. Each value is looked up as a key, and any value with no matching key becomes NaN. A missing input does not match a key, so it also becomes NaN.
This causes confusion. A NaN in the result can mean either "the input was missing" or "the input had no entry in the dict". The output alone does not tell you which.
import numpy as np
import pandas as pd
s = pd.Series(["a", np.nan, "z"])
mapping = {"a": "x"}
print(s.map(mapping))0 x
1 NaN
2 NaN
dtype: objectRows 1 and 2 look the same but have different causes. If you want to label unmapped values and leave real missing values alone, a function with dict.get and na_action="ignore" does it:
import numpy as np
import pandas as pd
s = pd.Series(["a", np.nan, "z"])
mapping = {"a": "x"}
print(s.map(lambda v: mapping.get(v, "other"), na_action="ignore"))0 x
1 NaN
2 other
dtype: objectThe shorter s.map(mapping).fillna("other") is correct only if every missing input should also become "other". It cannot tell the two cases apart, because the missing values are already merged by the time fillna runs.
Series.apply has no na_action
Series.apply does not take na_action. Any extra keyword arguments to apply are forwarded to your function. Writing s.apply(str.upper, na_action="ignore") would pass na_action to str.upper as an argument, and that call would fail.
With apply, the function has to handle missing values itself. The usual way is to test with pd.isna and return early:
import numpy as np
import pandas as pd
def shout(x):
if pd.isna(x):
return x
return x.upper() + "!"
s = pd.Series(["a", np.nan, "c"])
print(s.apply(shout))0 A!
1 NaN
2 C!
dtype: objectpd.isna is the right test because it works for NaN, None, pd.NA and NaT. The common alternatives each have a problem:
x == np.nanis alwaysFalse, becauseNaNis not equal to anything, including itself.x is NonemissesNaN, which is what most numeric columns contain.if not xtreats0and""as missing, and it raisesTypeErroronpd.NA.
The function above returns the missing value it was given. Returning x is often better than returning np.nan. It keeps the original marker, and it avoids a dtype change when the column uses a nullable type.
A function can also return a different value for missing input, such as a default:
import numpy as np
import pandas as pd
def label(x):
return "unknown" if pd.isna(x) else x.title()
names = pd.Series(["ada", np.nan, "grace"])
print(names.apply(label))0 Ada
1 unknown
2 Grace
dtype: objectHere missing input is replaced with a new value. Do this on purpose, because it removes the missing marker from the data. Later isna, dropna and fillna calls will no longer find those rows.
Prefer built-in methods that already skip missing values
Many things people do with map or apply have a built-in pandas method that handles missing values for you. The string accessor is the standard example:
import numpy as np
import pandas as pd
s = pd.Series(["a", np.nan, "c"])
print(s.str.upper())This gives the same result as the na_action="ignore" version, and it is usually faster. Methods such as .dt for dates, .fillna, .where and arithmetic operators also propagate missing values without extra code. A custom function is justified when no built-in method does what you need. A later chapter covers vectorized alternatives in more detail.
Choosing a strategy
| Goal | Tool |
|---|---|
| Run a function only on non-missing values, keep missing values as they are | `s.map(func, na_action="ignore")` |
| Same, with `apply` | Test with `pd.isna(x)` inside the function and return `x` |
| Replace missing values with a default | `s.fillna(default)` before or after the call |
| Treat unmapped dict keys and missing inputs differently | `map` with `dict.get` and `na_action="ignore"` |
| Operation exists as a built-in method | Use the method, for example `s.str.upper()` |
The same na_action parameter exists on DataFrame.map from pandas 2.1, where it applies to each cell. A later chapter covers that method.
Common errors
- A TypeError or ValueError only on some data. The function fails only when a missing value is present. Check with
s.isna().any()and then addna_action="ignore"or anisnaguard. - A numeric column became float. Missing values force
float64. Use a nullable dtype such asInt64if you need integers with gaps. - Using
==to detect missing values. Usepd.isnaorSeries.isna. - Assuming
applyacceptsna_action. It does not. The argument is forwarded to your function. - Filling too early. Calling
fillnabeforemapcan hide missing data that you wanted to count. Calling it aftermapfills both original gaps and unmapped values, so decide which you want.
Exercises
Exercise
Given s = pd.Series([4.0, np.nan, 9.0]), write one line that applies math.sqrt to every non-missing value and leaves the missing one as NaN. Why is na_action="ignore" needed here? Assume import math.
Show answer
s.map(math.sqrt, na_action="ignore"). Without it, math.sqrt receives NaN. It returns NaN for a float NaN, so this case might not fail, but with None or pd.NA in the Series the call would raise TypeError. Skipping missing values explicitly makes the code behave the same for every missing marker.
Exercise
A Series of country codes is ["us", "de", np.nan, "xx"], and the dict is {"us": "United States", "de": "Germany"}. You want unknown codes to become "Unknown" while the missing value stays NaN. Why is s.map(mapping).fillna("Unknown") wrong, and what is a correct version?
Show answer
fillna runs after the lookup, when the missing input and the unmapped "xx" are both NaN, so both become "Unknown". A correct version is s.map(lambda c: mapping.get(c, "Unknown"), na_action="ignore"). The missing value is skipped and stays NaN, and "xx" falls back to "Unknown".
Exercise
Write a function for Series.apply that returns the length of each string and returns np.nan for missing entries, without using na_action. Which function tests for missing values, and why not use x == np.nan?
Show answer
def length(x): return np.nan if pd.isna(x) else len(x). Use it as s.apply(length). pd.isna works for NaN, None, pd.NA and NaT. x == np.nan is always False because NaN is never equal to anything, including itself.