Pandas: Series - map() function
Map values of Pandas Series
The map() function is used to map values of Series according to input correspondence.
Used for substituting each value in a Series with another value, that may be derived from a function, a dict or a Series.
Syntax:
Series.map(self, arg, na_action=None)
Parameters:
Name | Description | Type/Default Value | Required / Optional |
---|---|---|---|
arg | Mapping correspondence. | function, dict, or Series | Required |
na_action | If ‘ignore’, propagate NaN values, without passing them to the mapping correspondence. | {None, ‘ignore’} Default Value : None |
Required |
Returns: Series
Same index as caller.
Notes: When arg is a dictionary, values in Series that are not in the dictionary (as keys) are converted to NaN. However, if the dictionary is a dict subclass that defines __missing__ (i.e. provides a method for default values), then this default is used rather than NaN.
Example:
Python-Pandas Code:
import numpy as np
import pandas as pd
s = pd.Series(['fox', 'cow', np.nan, 'dog'])
s
Output:
0 fox 1 cow 2 NaN 3 dog dtype: object
Example - map accepts a dict or a Series. Values that are not found in the dict are converted to NaN, unless the dict has a default value (e.g. defaultdict):
Python-Pandas Code:
import numpy as np
import pandas as pd
s = pd.Series(['fox', 'cow', np.nan, 'dog'])
s.map({'fox': 'cub', 'cow': 'calf'})
Output:
0 cub 1 calf 2 NaN 3 NaN dtype: object
Example - It also accepts a function:
Python-Pandas Code:
import numpy as np
import pandas as pd
s = pd.Series(['fox', 'cow', np.nan, 'dog'])
s.map('I am a {}'.format)
Output:
0 I am a fox 1 I am a cow 2 I am a nan 3 I am a dog dtype: object
Example - To avoid applying the function to missing values (and keep them as NaN) na_action='ignore' can be used:
Python-Pandas Code:
import numpy as np
import pandas as pd
s = pd.Series(['fox', 'cow', np.nan, 'dog'])
s.map('I am a {}'.format)
s.map('I am a {}'.format, na_action='ignore')
Output:
0 I am a fox 1 I am a cow 2 NaN 3 I am a dog dtype: object
Previous: Call function on self producing a Series in Pandas
Next: Splitting the object in Pandas
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/pandas/series/series-map.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics