Sub topic 2
Transforming a Series with map
This chapter assumes you can write Python functions and lambda expressions, create and index a pandas Series, and assign a new column to a DataFrame. It covers Series.map when you pass it a function. Passing a dict or another Series, the na_action option, and the comparison with apply each get their own chapter, so this one only touches them where needed.
What map does
Series.map calls your function once for each element of a Series. It collects the return values into a new Series. 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 prints A, B, C. The second prints aa, bb, cc. Both results have the index 0, 1, 2 and dtype object.
The function receives one scalar value at a time, never a whole column. For a Series of strings, your function gets a Python str. For an integer Series, it gets a number. The signature is:
Series.map(arg, na_action=None)arg can be a function, a dict, or a Series. na_action is either None (the default) or "ignore".
The diagram shows what happens inside one call.
The index is preserved
The result has the same index as the input, in the same order. The function never sees the index labels, only the values.
import pandas as pd
s = pd.Series([3, 5, 8], index=["x", "y", "z"])
squared = s.map(lambda v: v ** 2)
print(squared)x 9
y 25
z 64
dtype: int64Because the index is kept, you can assign the result straight into a DataFrame column. Pandas aligns on the index, so the values land on the matching rows.
Passing named functions, built-ins and lambdas
Any callable that accepts one positional argument works. These are the common choices:
- A built-in such as
len,abs,str, orfloat. - An unbound method such as
str.upperorstr.strip. - A lambda for a short one-off expression.
- A function you defined with
def, which is easier to test and name.
import pandas as pd
names = pd.Series([" apple ", "Banana", "cherry "])
print(names.map(str.strip))
print(names.map(len))The first call returns apple, Banana, cherry. The second returns the lengths 7, 6, 7, because len counts the spaces.
Pass the function itself and do not call it. Write s.map(str.upper), not s.map(str.upper()). A lambda is the usual choice when you need a small calculation. Once the logic has a branch or needs a comment, use a named function.
import pandas as pd
def grade(score):
if score >= 90:
return "high"
if score >= 60:
return "pass"
return "fail"
scores = pd.Series([95, 72, 40, 60])
print(scores.map(grade))This prints high, pass, fail, pass. A named function also lets you test the logic without pandas: grade(72) returns "pass".
Proving that the function is called per element
If you want to see the calling pattern, record the arguments:
import pandas as pd
calls = []
def record(x):
calls.append(x)
return x + 1
result = pd.Series([1, 2, 3]).map(record)
print(calls)
print(result.tolist())The output is [1, 2, 3] and then [2, 3, 4]. The function is a plain Python loop body here. Each call has the interpreter overhead of a normal function call. This is why map is flexible but slower than built-in vectorized operations, a point the chapter on vectorized alternatives covers in detail.
How the result dtype is chosen
Pandas looks at the values your function returns and infers a dtype for the new Series. You do not declare it.
import pandas as pd
n = pd.Series([1, 2, 3])
print(n.map(lambda v: v / 2).dtype)
print(n.map(lambda v: v > 1).dtype)
print(n.map(lambda v: f"item-{v}").dtype)The three lines print float64, bool, and object. Strings are stored as object by default. Newer pandas versions may use a dedicated string dtype when that option is enabled.
Inference has two consequences you should know about.
- If the function returns an integer for some elements and a float for others, the result becomes
float64. If it returns numbers for some elements and strings for others, the result isobject, which is slow and awkward to work with. - If you need a specific dtype, convert afterwards with
.astype(...)instead of hoping inference gives the right one.
Returning containers
A function can return a list, tuple, or dict. The Series then holds one container per row, with dtype object. Pandas does not expand it into columns.
import pandas as pd
s = pd.Series(["2024-05-17", "2023-11-02"])
parts = s.map(lambda d: tuple(int(p) for p in d.split("-")))
print(parts)
table = pd.DataFrame(parts.tolist(), index=s.index, columns=["year", "month", "day"])
print(table)parts holds the tuples (2024, 5, 17) and (2023, 11, 2). The second step builds a DataFrame with year, month, and day columns. Passing index=s.index keeps the original labels.
If your goal is several output columns, DataFrame.apply or a vectorized string method such as s.str.split("-", expand=True) is often a better fit. A later chapter covers return shapes in detail.
Exceptions and bad data
An exception inside your function stops the whole map call. You get no partial result, and the traceback points into pandas internals before reaching your function. The usual cause is data your function did not expect.
import pandas as pd
raw = pd.Series(["10", "20", "n/a", "40"])
def to_int_or_none(text):
try:
return int(text)
except ValueError:
return None
parsed = raw.map(to_int_or_none)
print(parsed)Here int("n/a") would raise ValueError and abort the call. Catching the exception inside the function turns bad input into a missing value. Because None and integers are mixed, pandas stores the result as float64 with NaN for the failed element: 10.0, 20.0, NaN, 40.0.
Catch only the exception types you expect. A bare except: hides real bugs.
For this particular job, pd.to_numeric(raw, errors="coerce") does the same thing in compiled code. Check whether pandas already has a function for your transformation before writing your own.
Missing values reach your function
By default, map passes missing values (NaN, None) to your function like any other element. Methods such as str.upper fail on them with a TypeError.
import pandas as pd
s = pd.Series(["a", None, "c"])
print(s.map(str.upper, na_action="ignore"))With na_action="ignore", pandas skips the missing element. It does not call your function for it, and the result keeps the missing value in that position. The output is A, None, C. The next chapter in this tutorial covers na_action in full, including how it interacts with dict lookups.
Where map is a poor fit
map shows up in many beginner pandas scripts, but it is not always the best tool. Consider these cases before reaching for it.
| Task | A better option than map with a lambda |
|---|---|
| Arithmetic on a numeric column | A vectorized expression such as `s * 2` or `s ** 2` |
| String cleanup | The `.str` accessor, for example `s.str.strip().str.lower()` |
| Replacing a few known values | `s.replace({...})` or `map` with a dict |
| Parsing numbers or dates | `pd.to_numeric` and `pd.to_datetime` |
| Logic that needs several columns | `DataFrame.apply(axis=1)` or a vectorized expression across columns |
map is the right choice when each output depends only on one value, no built-in does the job, and the Series is small enough that Python-level speed is acceptable. Typical examples are custom parsing of a messy text format, calling a helper from another library, or a business rule with several branches.
Categorical columns
A Series with category dtype behaves differently. Pandas applies the function to the categories, not to every row, and then uses the codes to fill the result. For a column with three distinct categories and a million rows, your function runs three times.
This is usually a speed gain, but it means a function with side effects (such as appending to a log) runs fewer times than the row count. Keep functions passed to map free of side effects.
Common mistakes
- Calling the function.
s.map(f())passes the return value off(), notf. This usually raises aTypeErroror silently does something unexpected. - Expecting to modify in place.
s.map(f)returns a new Series. Assign it withs = s.map(f)ordf["col"] = df["col"].map(f). - Needing a second argument. Your function receives exactly one value. To fix a second parameter, wrap it:
s.map(lambda v: add_tax(v, 0.2)), or usefunctools.partial(add_tax, rate=0.2).Series.apply, covered later, forwards extra arguments for you. - Forgetting that results can change dtype. Check
result.dtypewhen the output feeds later calculations. - Looping over the index with map. The function sees values only. If you need labels, use
s.indexdirectly or iterate withs.items().
Summary of behavior
maptakes a callable and calls it once per element.- The function receives scalar values, not the index.
- The result is a new Series with the same index and an inferred dtype.
- Returned containers stay as single objects in an
objectSeries. - Exceptions abort the call. Missing values are passed to the function unless you set
na_action="ignore".
Exercise
Given s = pd.Series(["7", "x", "12"], index=["a", "b", "c"]), write one map call that returns the integers where possible and None where the text is not a number. What index and dtype does the result have?
Show answer
Define def to_int(t): with try: return int(t) and except ValueError: return None, then use s.map(to_int). The index stays a, b, c. The values are 7.0, NaN, 12.0, and the dtype is float64, because pandas converts the None to NaN when the other values are numbers.
Exercise
Why does pd.Series([1, 2, 3]).map(lambda v: [v, v]) produce a Series and not a DataFrame with two columns? How would you get a DataFrame?
Show answer
map stores whatever your function returns as one element per row, so each row holds a list and the dtype is object. To get columns, build a DataFrame from the lists, for example pd.DataFrame(result.tolist(), index=result.index).
Exercise
A categorical column has 4 distinct values and 100,000 rows. Roughly how many times does a function passed to map run, and why does it matter if the function has side effects?
Show answer
About 4 times, because pandas applies the function to the categories and then expands the result using the category codes. A side effect such as logging or appending to a list therefore happens 4 times, not 100,000 times.