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 |
0 | Alice | 5 |
1 | Bob | 3 |
2 | Charlie | 7 |
3 | David | 5 |
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 |
0 | hello | 5 |
1 | HELLO | 5 |
2 | 1234 | 4 |
3 | space | 8 |
4 | | 0 |
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 |
0 | Alice | Smith | 5 | 5 |
1 | Bob | Jones | 3 | 5 |
2 | Charlie | Brown | 7 | 5 |
3 | David | Davis | 5 | 5 |
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.