Sub topic 1
Passing Your Own Functions to pandas
Prerequisites
Assume you know basic Python functions and lambda expressions, and can create, index, and assign values in pandas Series and DataFrame objects.
A callable is a function that pandas can run. Methods such as map and apply accept a callable, call it for selected data, and collect the results.
Transforming a Series with `map`
Series.map applies a function to each value and returns a new Series. The original series is unchanged.
import pandas as pd
letters = pd.Series(["a", "b", "c"])
doubled = letters.map(lambda value: value * 2)
print(doubled)The lambda receives one value at a time. Use map when the operation is element by element.
Mapping Values with a Dict or Series
map also accepts a dictionary or another Series as a lookup mapping. Each original value is matched against a key or index. An unmatched value becomes NaN.
import pandas as pd
codes = pd.Series(["us", "ca", "xx"])
names = codes.map({"us": "United States", "ca": "Canada"})
print(names)A Series lookup works similarly. Its index provides the keys, and its values provide the replacements.
labels = pd.Series(
["United States", "Canada"],
index=["us", "ca"]
)
print(codes.map(labels))Use a lookup mapping for direct replacement. Use a function when the result depends on computation.
Missing Values and `na_action`
Missing values can cause a function to fail. For example, str.upper cannot operate on None. Set na_action="ignore" to leave missing values unchanged instead of passing them to the function.
import pandas as pd
values = pd.Series(["open", None, "closed"])
result = values.map(str.upper, na_action="ignore")
print(result)The missing entry remains missing. This option applies when map receives a function. With a dictionary or Series lookup, unmatched keys also produce missing results.
Exercise
Which method is appropriate for replacing "S" with "small" and "L" with "large" using a fixed set of replacements?
Show answer
Use Series.map({"S": "small", "L": "large"}). A dictionary expresses direct lookup clearly.