Find the length of the string in dataframe – Python Pandas

Blog-34.jpg

To find the length of the string in a dataframe, we can use str.len() function. In this blog, we will learn this concept in more detail.

Table of Contents:

Find the length of the string in dataframe of Python Pandas

In Python Pandas dataframe, we can find the length of the string by using str.len() function. Let’s learn this with an example:

Syntax:

df['column_name'].str.len()

Where df is the dataframe, and column_name is the name of the column that contains string values.

Example:

Python

Output:

Name Name_Length
0Alice5
1Bob3
2Charlie7
3David5

Practical Examples to Find the Length of the String in a dataframe

Example 1: Find the length of strings in a single column

Code:

Python

Output:

Text Text_Length
0hello5
1HELLO5
212344
3space8
40

Explanation: Here we have printed multiple formats of data, where ‘   space’ this string length is 8 because of 3 extra spaces.

Example 2: Find the length of strings in multiple columns

Code:

Python

Output:

First_Name Last_Name First_Name_Length Last_Name_Length
0AliceSmith 55
1BobJones 35
2CharlieBrown75
3DavidDavis55

Explanation: Here, we have stored the length of both the first name and the last name and printed the dataframe.

Conclusion

So far in this article, we have learned how we can find the length of a string in a Python pandas dataframe with the help of some practical examples. If you want to learn more about Python, you may refer to our Python course.

About the Author

Data Scientist | Technical Research Analyst - Analytics & Business Intelligence

Lithin Reddy is a Data Scientist and Technical Research Analyst with around 1.5 years of experience, specializing in Python, SQL, system design, and Power BI. Known for building robust, well-structured solutions and contributing clear, practical insights that address real-world development challenges.

EPGC Data Science Artificial Intelligence