Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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
xto a string usingstr(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.
