Open In App

Python | pandas.map()

Pandas is a widely used library for manipulating datasets. There are various in-built functions of pandas, one such function is pandas.map(), 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:

Series.map(arg, na_action=None)



Parameters:

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: ")
s.map({'cat': 'kitten', 'cow': 'calf'})

Output:

Series:
0    cat
1    cow
2    dog
dtype: object

Mapping: 
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'])
s.map('This is a {}'.format)

Output:

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: ")
print(df)
 
mappings = {
    'carrot': 'veg',
    'papaya': 'fruit'
}
 
df['type_name'] = df['species'].map(mappings)
print("Dataframe after Mapping: ")
print(df)

Output:

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.


Article Tags :
Uncategorized