Write a program in Python to print the length of elements in all column in a dataframe using applymap

The applymap() function in Pandas allows you to apply a function element-wise to every cell in a DataFrame. This is useful when you want to calculate the length of string elements across all columns.

Understanding applymap()

The applymap() method applies a function to each element of the DataFrame. Unlike apply(), which works on rows or columns, applymap() works on individual elements.

Syntax

DataFrame.applymap(func)

Where func is the function to apply to each element.

Example

Let's create a DataFrame and calculate the length of elements in all columns ?

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({
    'Fruits': ["Apple", "Orange", "Mango", "Kiwi"],
    'City': ["Shimla", "Sydney", "Lucknow", "Wellington"]
})

print("Original DataFrame:")
print(df)
Original DataFrame:
   Fruits       City
0   Apple     Shimla
1  Orange     Sydney
2   Mango    Lucknow
3    Kiwi  Wellington

Calculating Length of Elements

Now we'll use applymap() with a lambda function to calculate the length of each element ?

import pandas as pd

df = pd.DataFrame({
    'Fruits': ["Apple", "Orange", "Mango", "Kiwi"],
    'City': ["Shimla", "Sydney", "Lucknow", "Wellington"]
})

# Apply length function to all elements
length_df = df.applymap(lambda x: len(str(x)))

print("Length of elements in all columns:")
print(length_df)
Length of elements in all columns:
   Fruits  City
0       5     6
1       6     6
2       5     7
3       4     10

How It Works

The lambda function lambda x: len(str(x)) does the following:

  • Converts each element x to a string using str(x)

  • Calculates the length using len()

  • Returns the length as an integer

Alternative Approach

You can also define a separate function instead of using lambda ?

import pandas as pd

def get_length(element):
    return len(str(element))

df = pd.DataFrame({
    'Fruits': ["Apple", "Orange", "Mango", "Kiwi"],
    'City': ["Shimla", "Sydney", "Lucknow", "Wellington"]
})

length_df = df.applymap(get_length)
print("Length using custom function:")
print(length_df)
Length using custom function:
   Fruits  City
0       5     6
1       6     6
2       5     7
3       4     10

Conclusion

Use applymap() with lambda x: len(str(x)) to calculate the length of all elements in a DataFrame. This method works element-wise and converts each value to string before calculating length.

Updated on: 2026-03-25T16:26:11+05:30

416 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements