Pandas Series | map method
Start your free 7-days trial now!
Pandas Series.map(~)
method applies a mapping to each value of the Series. The mapping is not applied inplace, that is, a new Series is returned.
Parameters
1. arg
| function
or dict
or Series
The mapping to apply to each value of the Series. Check out the examples below for clarification.
2. na_action
link | None
or string
| optional
If
None
, then the mapping is also applied toNaN
values.If
"ignore"
, then no mapping is applied toNaN
values.
By default, na_action=None
.
Return Value
A Series
with the mapping applied.
Examples
Applying a function
To apply a function to a Series:
s.map(lambda x: x+5)
0 71 8dtype: int64
Here, a new Series is returned, so the original s
is kept intact.
Applying a mapping
We can pass a dict
or Series
to map each value of the source Series to another value:
s.map({"a":"A"})
0 A1 NaNdtype: object
Notice how since 3
is not present as a a key in our dict
, we get a NaN
for that entry.
Specifying na_action
By default, na_action=None
, which means that NaN
values are also passed into the mapping function:
s = pd.Series([2,None,3])s.map(lambda x: 5 if pd.isna(x) else 10) # na_action=None
0 101 52 10dtype: int64
Setting to na_action="ignore"
means that no mapping is applied to NaN
values:
s = pd.Series([2,None,3])s.map(lambda x: 5 if pd.isna(x) else 10, na_action="ignore")
0 10.01 NaN2 10.0dtype: float64