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
Selected Reading
Write a program in Python to print the length of elements in all column in a dataframe using applymap
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
Advertisements
