Find the length of the string in dataframe - Python Pandas

Find the length of the string in dataframe - Python Pandas

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:

import pandas as pd

data = {'Name': ['Alice', 'Bob', 'Charlie', 'David']}
df = pd.DataFrame(data)

df['Name_Length'] = df['Name'].str.len()
print(df)

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:

import pandas as pd

df = pd.DataFrame({
    'Text': ['hello', 'HELLO', '1234', '   space', '']
})

df['Text_Length'] = df['Text'].str.len()
print(df)

Output:

Text Text_Length
0hello5
1HELLO5
212344
3space8
40

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

Example 2: Find the length of strings in multiple columns

Code:

import pandas as pd

df = pd.DataFrame({
    'First_Name': ['Alice', 'Bob', 'Charlie', 'David'],
    'Last_Name': ['Smith', 'Jones', 'Brown', 'Davis']
})

df['First_Name_Length'] = df['First_Name'].str.len()
df['Last_Name_Length'] = df['Last_Name'].str.len()

print(df)

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 first name and 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 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

Senior Consultant Analytics & Data Science

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration. 

Full Stack Developer Course Banner