Pandas – Map

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(selfargna_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

.     .     .

Leave a Reply

Your email address will not be published. Required fields are marked *

Python Pandas Tutorials

Pandas – How to remove DataFrame columns with constant (same) values?

Pandas – How to remove DataFrame columns with only one distinct value?

Pandas – Count unique values for each column of a DataFrame

Pandas – Count missing values (NaN) for each columns in DataFrame

Pandas – MultiIndex

Pandas – Applymap

Pandas – Apply

Pandas – Missing Data

Difference between Merge, join, and concatenate

Pandas – Join

pandas : Handling Duplicate Data

Pandas : Handling Categorical Data

Pandas : Data Types

Appending a row to DataFrame

Python Pandas – Merge

Python Pandas – Concatenation & append

Python Pandas – GroupBy

Python Pandas – Visualization

Python Pandas – Options and Customization

Python Pandas – Descriptive Statistics

Python Pandas – Basic functions

Python Pandas – DataFrame

Python Pandas – Series

Python Pandas – Introduction