Print Length of Elements in DataFrame using applymap in Python



The result for the length of elements in all column in a dataframe is,

Dataframe is:
   Fruits    City
0 Apple    Shimla
1 Orange   Sydney
2 Mango    Lucknow
3 Kiwi    Wellington
Length of the elements in all columns
   Fruits City
0    5    6
1    6    6
2    5    7
3    4    10

Solution

To solve this, we will follow the steps given below −

  • Define a dataframe

  • Use df.applymap function inside lambda function to calculate the length of elements in all column as

df.applymap(lambda x:len(str(x)))

Example

Let’s check the following code to get a better understanding −

import pandas as pd
df = pd.DataFrame({'Fruits': ["Apple","Orange","Mango","Kiwi"],
                     'City' : ["Shimla","Sydney","Lucknow","Wellington"]
                  })
print("Dataframe is:\n",df)
print("Length of the elements in all columns")
print(df.applymap(lambda x:len(str(x))))

Output

Dataframe is:
  Fruits    City
0 Apple    Shimla
1 Orange   Sydney
2 Mango    Lucknow
3 Kiwi    Wellington
Length of the elements in all columns:
   Fruits City
0    5    6
1    6    6
2    5    7
3    4    10
Updated on: 2021-02-25T05:58:11+05:30

342 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements