Pandas – Applymap

Pandas’ applymap() method apply a function to a Dataframe elementwise. This method applies a function that accepts and returns a scalar to every element of a DataFrame.

The main difference between apply() and applymap() method is:

  • Pandas’ apply() method work on row/column basis of a DataFrame.
  • Pandas’ applymap() method work element-wise on a DataFrame.

 

Syntax:

DataFrame.applymap(selffunc)

Parameters:

func - Python function,  returns a single value from a single value.

Let’s see the examples:

In [1]:
# Define the DataFrame
import pandas as pd
df = pd.DataFrame([['Mark','Johnathn'], ['Juli','Alexa']], columns=list('AB'))
df

Out[1]:
      A         B
0  Mark  Johnathn
1  Juli     Alexa

Find the length of each element of the DataFrame.

In [2]: df.applymap(lambda x: len(x))
Out[2]:
   A  B
0  4  8
1  4  5

# apply() function count the number of element in specified axis.

In [3]: df.apply(lambda x: len(x),axis=0)
Out[3]:
A    2
B    2
dtype: int64

When to use apply()?

If you want to work with the entire axis either row/column, use apply() function. Let’s see the example of subtracting each value from the max value of its column.

In [4]:
df = pd.DataFrame([[1,2], [6, 1], [9,5],[1 ,4]], columns=list('AB'))
df
Out[4]:
   A  B
0  1  2
1  6  1
2  9  5
3  1  4

In [5]: df.apply(lambda x: x.max()-x)   
Out[5]:
   A  B
0  8  3
1  3  4
2  0  0
3  8  1

when to use applymap()?

If you want to perform some operation on element-wise, use applymap() function.

In [6]: df
Out[6]:
   A  B
0  1  2
1  6  1
2  9  5
3  1  4

In [7]: df.applymap(lambda x: x*2)
Out[7]:
    A   B
0   2   4
1  12   2
2  18  10
3   2   8

.      .      .

Leave a Reply

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

Python Pandas Tutorials