Python Pandas: Find the length of the string in dataframe

8.4K    Asked by IraJoshi in Python , Asked on Apr 14, 2021

 How to find find the length of dataframe  string stored in each cell. What code should I use to do this?

Answered by Ira Joshi

To find the length of strings in a data frame you have the len method on the dataframes str property. But to do this you need to call this method on the column that contains the string data.

You can find the length of dataframe using the below code:

import pandas as pd
data = pd.DataFrame({
    'age' : [15, 17, 20, 14, 25],
    'name': ["Sample", "New User", "My Name", "Jane Doe", "John Doe"]
})
data['name'].str.len()
You'll get the following output:
0 6
1 8
2 7
3 8
4 8
Name: name, dtype: int64

Your Answer

Answer (1)

To find the length of strings in a DataFrame column using Python Pandas, you can use the str.len() method. Here's how you can do it:

import pandas as pd
# Create a sample DataFrame
data = {'Name': ['John', 'Alice', 'Bob', 'Charlie'],
        'City': ['New York', 'Los Angeles', 'Chicago', 'Boston']}
df = pd.DataFrame(data)
# Add a new column with the length of strings in the 'Name' column
df['Name_Length'] = df['Name'].str.len()
# Display the DataFrame
print(df)

Output:

     Name         City  Name_Length
0 John New York 4
1 Alice Los Angeles 5
2 Bob Chicago 3
3 Charlie Boston 7

In this example, we first create a DataFrame with columns 'Name' and 'City'. Then, we use the str.len() method to compute the length of strings in the 'Name' column and assign the result to a new column 'Name_Length'. Finally, we print the DataFrame to see the result.

6 Months

Interviews

Parent Categories