Sub topic 2
Transforming a Series with map
This chapter assumes you can write short Python functions and lambdas, create a pandas Series, and assign a new column to a DataFrame. Here you will use Series.map to transform a Series one element at a time.
What map does
Series.map calls a function once for each element of a Series. It returns a new Series with the same index and the results as its values. The original Series is not changed.
import pandas as pd
s = pd.Series(["a", "b", "c"])
print(s.map(str.upper))
print(s.map(lambda x: x * 2))The first call passes each string to str.upper. The second call uses a lambda that repeats each string, so "a" becomes "aa". Both calls print a Series with index 0, 1 and 2.
Pass the function itself, as in str.upper. Do not call it, as in str.upper(). Pandas does the calling.
Mapping with a dict
map also accepts a dict. Pandas looks up each element as a key and uses the matching value. This suits recoding tasks, such as turning codes into labels.
import pandas as pd
s = pd.Series(["a", "b", "c"])
print(s.map({"a": "x", "b": "y"}))The key "c" is not in the dict, so its result is NaN. A dict never raises an error for a missing key. Check the output for unexpected NaN values after you map.
A Series also works as the lookup. Its index supplies the keys and its values supply the results.
import pandas as pd
codes = pd.Series(["north", "south"], index=["N", "S"])
regions = pd.Series(["N", "S", "N"])
print(regions.map(codes))This prints north, south, north.
Missing values and na_action
By default, map passes missing values to your function too. Many functions fail on them. str.upper(None) raises a TypeError, for example. Set na_action="ignore" to skip missing values. They stay missing in the result.
import pandas as pd
s = pd.Series(["a", None, "c"])
print(s.map(str.upper, na_action="ignore"))The output is A, None, C. Your function never sees the None.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `TypeError` inside your function | A missing value reached the function | Use `na_action="ignore"` or handle missing values in the function |
| Unexpected `NaN` in the result | A dict or Series lookup had no matching key | Add the missing keys, or fill afterwards with `fillna` |
| `TypeError` about a Series not being callable | You wrote `s.map(f())` instead of `s.map(f)` | Pass the function without parentheses |
| Result looks unchanged | You did not keep the returned Series | Assign it, for example `df["col"] = df["col"].map(f)` |
When map is the right tool
Use map when each output depends only on one input element. It is a good fit for recoding values with a dict, or for applying a small function to one column. It cannot take extra arguments for your function, and it cannot see other elements or columns. The next chapters cover apply for those cases.
Exercise
A Series s = pd.Series(["lo", "hi", None, "lo"]) must become 0 for "lo" and 1 for "hi", with the missing value left missing. Which call do you use, and what does the missing entry become?
Show answer
Use s.map({"lo": 0, "hi": 1}). The None is looked up as a key, finds no match, and becomes NaN. The result is 0.0, 1.0, NaN, 0.0. The dtype is float because NaN is a float.
Exercise
Why does pd.Series(["a", None]).map(str.upper) fail, and how do you fix it?
Show answer
map passes None to str.upper, which raises a TypeError because None is not a string. Add na_action="ignore" so the missing value is skipped and stays missing in the result.