Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

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

2 Answers

0 votes
by (25.1k points)
edited by

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.

For example:

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

You can learn more about pandas and other data science libraries by watching this video:

0 votes
by (1.9k points)

To get the length of the string stored in each cell of a DataFrame in Python using pandas, you can use the.applymap() method along with the built-in len() function. Here is how you can do it:

import pandas as pd

data = {'Column1': ['apple', 'banana', 'cherry'], 'Column2': ['dog', 'elephant', 'cat']} 

df = pd.DataFrame(data) 

lengths = df.applymap(len) 

print(lengths)

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...