Open In App
Related Articles

Python |

Improve Article
Save Article
Like Article

Pandas is a widely used library for manipulating datasets. There are various in-built functions of pandas, one such function is, which is used to map values from two series having one similar column. For mapping two series, the last column of the first should be the same as the index column of the second series, also the values should be unique.

Let’s see what is the syntax, parameters, and return type of this function.

Syntax:, na_action=None)


arg : function, dict, or Series
na_action : {None, ‘ignore’} If ‘ignore’, propagate NA values, without passing them to the mapping correspondence. na_action checks the NA value and ignores it while mapping in case of ‘ignore’

Return type:

Pandas Series with same as index as caller

Example 1:

In this example, we will take a series and then apply the map function.


import pandas as pd
s = pd.Series(['cat', 'cow', 'dog'])
print("Series:\n", s)
print("Mapping: "){'cat': 'kitten', 'cow': 'calf'})


0    cat
1    cow
2    dog
dtype: object

0    kitten
1      calf
2       NaN
dtype: object

Example 2:

We can also directly pass a function to the map. Let’s see its implementation.


import pandas as pd
s = pd.Series(['lily', 'rose','lotus'])'This is a {}'.format)


0     This is a lily
1 This is a rose
2 This is a lotus
dtype: object

Example 3:

In this example we will take a dataframe, then we will apply map function to it.


import pandas as pd
df = pd.DataFrame(
    [('carrot', 'red', 1),
     ('papaya', 'yellow', 0),
     ('mango', 'yellow', 0),
     ('apple', 'red', 0)
    columns=['species', 'color', 'type']
print("Dataframe before Mapping: ")
mappings = {
    'carrot': 'veg',
    'papaya': 'fruit'
df['type_name'] = df['species'].map(mappings)
print("Dataframe after Mapping: ")


Dataframe before Mapping: 
species color type
0 carrot red 1
1 papaya yellow 0
2 mango yellow 0
3 apple red 0

Dataframe after Mapping:
species color type type_name
0 carrot red 1 veg
1 papaya yellow 0 fruit
2 mango yellow 0 NaN
3 apple red 0 NaN

Note: Values that are not in the dictionary but are in the dataframe/series are assigned with Nan unless dictionary have a default value.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 23 Aug, 2023
Like Article
Save Article
Similar Reads
Related Tutorials