Pandas map() function used to substituting each value in Series or column of DataFrames. The substituted value may be derived from a dictionary, a function or a Series. In this tutorial, You will learn how to use the map() function with examples.
Syntax:
Series.
map
(self, arg, na_action=None)
Parameters:
arg -function, dict, or Series. Mapping correspondence.
na_action - {None, ‘ignore’}, default None
If ‘ignore’, propagate NaN values, without passing them to the
mapping correspondence.
Examples:
In [1]: import pandas as pd dix = {'A':1,'B':2,'C':3,'D':4} # Defined Dict for mapping s = pd.Series(['A','C','D','B']) s.map(dix) Out[1]: 0 1 1 3 2 4 3 2 dtype: int64
In [2]: df = pd.DataFrame([[1,2], [6, 1], [9,5],[1 ,4]], columns=list('AB')) df Out[2]: A B 0 1 2 1 6 1 2 9 5 3 1 4
Map values using a function.
In [3]: def square(x): # Defined function for mapping return x*2 In [4]: df['B'].map(square) Out[4]: 0 4 1 2 2 10 3 8 Name: B, dtype: int64
Parameter na_action=’ignore’ used to avoid applying a function to missing values and keep them as NaN.
In [5]: s = pd.Series(['cat', 'dog', np.nan, 'rabbit']) In [6]: s.map('I am a {}'.format) Out[6]: 0 I am a cat 1 I am a dog 2 I am a nan 3 I am a rabbit dtype: object In [7]: s.map('I am a {}'.format, na_action='ignore') Out[7]: 0 I am a cat 1 I am a dog 2 NaN 3 I am a rabbit dtype: object
. . .