
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements