Sub topic 4
Missing values and na_action
This chapter assumes you can create a pandas Series, write a short Python function or lambda, and know that pandas marks missing values as NaN or None. It covers what happens to missing values when you call Series.map, and how na_action controls it.
What goes wrong without na_action
Series.map calls your function once for every element, including missing ones. If your function cannot handle a missing value, it fails. A missing value in a text column is often None or NaN, and NaN is a float. Calling a string method on it raises an error.
import pandas as pd
s = pd.Series(["a", None, "c"])
try:
print(s.map(str.upper))
except TypeError as err:
print("Failed:", err)str.upper is called with None as its argument, and that raises a TypeError. The error message names the function and the unexpected type, which tells you a missing value reached your code.
Skipping missing values with na_action
Pass na_action="ignore" to tell map not to send missing values to your function. pandas leaves those positions as missing in the result.
import pandas as pd
s = pd.Series(["a", None, "c"])
print(s.map(str.upper, na_action="ignore"))The output keeps the missing value in position 1:
0 A
1 None
2 C
dtype: objectThe default is na_action=None. In that mode the function sees every element, so you are responsible for handling missing values yourself.
Handling missing values inside the function
Sometimes you want a specific result for missing input instead of keeping it missing. Then leave na_action at its default and test for missing values in your function. pd.isna works for None, NaN and NaT.
import pandas as pd
def clean(value):
if pd.isna(value):
return "unknown"
return value.upper()
s = pd.Series(["a", None, "c"])
print(s.map(clean))Here the missing value becomes the string "unknown". With na_action="ignore" you could not do this, because your function would never see the missing value.
Missing values created by dict lookups
When you pass a dict to map, each element is looked up as a key. A value with no matching key becomes NaN, which is a missing value created by the mapping itself.
import pandas as pd
s = pd.Series(["a", "b", "c"])
print(s.map({"a": "x", "b": "y"}))The "c" element has no key, so the result is NaN. If you want a default instead, chain fillna:
import pandas as pd
s = pd.Series(["a", "b", "c"])
print(s.map({"a": "x", "b": "y"}).fillna("other"))na_action="ignore" also works with a dict. A missing input element is not looked up and stays missing.
Common mistakes
- Expecting NaN to be a string.
NaNis a float, soNaN.upper()raisesAttributeError, andstr.upper(NaN)raisesTypeError. - Using
x == Noneorx == np.nanto detect missing values. These comparisons do not work as intended. Usepd.isna(x). - Forgetting that the result dtype can change. A column of integers with one
NaNis stored as floats. Mapping over it passes floats to your function. - Using
na_action="ignore"and then expecting a replacement value. It only preserves the missing value. Usefillnaafterward or handle the case in the function.
Exercises
Exercise
A Series is pd.Series([1.5, None, 3.0]). You call .map(lambda x: round(x * 100)). This raises an error for the missing element. Write the call that keeps the missing value in the result instead of failing.
Show answer
s.map(lambda x: round(x * 100), na_action="ignore"). The missing element is not passed to the lambda, so the result at that position stays NaN.
Exercise
You want every missing city name in pd.Series(["Oslo", None, "Rome"]) to become "N/A", and every other name to be lowercased. Should you use na_action="ignore" or an isna check inside the function? Explain why.
Show answer
Use an isna check inside the function, for example lambda c: "N/A" if pd.isna(c) else c.lower(). With na_action="ignore" the function never sees the missing value, so it cannot return "N/A" for it. You could also use na_action="ignore" followed by .fillna("N/A").