Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas Series.str_len() function

Pandas Series.str_len() function

Pandas Common Functions Common Pandas functions


Series.str.len() is a function in Pandas used to compute string lengths.

During data processing, we often need to know string length information, such as validating input length, filtering text of a specific length, and analyzing text length distribution.len() The function returns the number of characters in each string element.

Word meaning:len is short for "length", meaning it returns the character count of the string.


Basic syntax and parameters

str.len() is a string accessor method of Series, so you need a Series containing strings first, and then call it through the .str accessor.

Syntax format



Series.str.len()

Parameter Description

Function description


Example

Let us thoroughly master str.len() through a series of examples from simple to complex.

Example 1: Basic Usage - Computing String Length

Example

import

pandas

as

pd

Create a Series with strings of varying lengths

s

=

pd.

Series

(

[

'hello'

,

'runoob'

,

'python'

,

'ai'

,

'data'

]

)

Use str.len() to compute the length of each string

result

=

s.

str

.

len

(

)

print

(

"Original Series:"

)

print

(

s

)

print

(

"nString lengths:"

)

print

(

result

)

Output result:



原始 Series:

0      hello

1     runoob

2     python

3        ai

4       data

dtype: object



String length:

0    5

1    6

2    6

3    2

4    4

Code analysis:

  1. s.str.len() Computes the character count of each string.
  2. 'hello' has 5 characters, returning 5.
  3. 'runoob' has 6 characters, returning 6.
  4. An empty string returns a length of 0.

Example 2: String Length Including Spaces

len() It counts all characters, including spaces.

Example

import

pandas

as

pd

Create a Series with spaces

s

=

pd.

Series

(

[

'hello world'

,

'runoob python'

,

'a b c'

,

'  space  '

]

)

Calculating string length

result

=

s.

str

.

len

(

)

print

(

"Original Series:"

)

print

(

s

)

print

(

"nString lengths (including spaces):"

)

print

(

result

)

Output result:



原始 Series:

0     hello world

1   runoob python

2           a b c

3          space

dtype: object



字符串长度(包括空格):

0    11

1    13

2          5

3          8

Code analysis:

Example 3: Filtering Strings of a Specific Length

len() Often used in combination with boolean indexing to filter data.

Example

import

pandas

as

pd

Create a product name Series

products

=

pd.

Series

(

[

'iPhone'

,

'Samsung Galaxy'

,

'MacBook Pro'

,

'iPad'

,

'Dell XPS'

]

)

Filter products with length greater than 8

long_names

=

products

[

products.

str

.

len

(

)

>

;

8

]

Filter products with length less than or equal to 5

short_names

=

products

[

products.

str

.

len

(

)

<

;=

5

]

print

(

"

;

All products:"

;

)

print

(

products

)

print

(

"

;

nLength greater than

8

products:"

;

)

print

(

long_names

)

print

(

"

;

nLength less than or equal to

5

products:"

;

)

print

(

short_names

)

Output result:



All products:

0            iPhone

1    Samsung Galaxy

2       MacBook Pro

3              iPad

4            Dell XPS

dtype: object



Products with length greater than 8:

1    Samsung Galaxy

2       MacBook Pro

4        Dell XPS

dtype: object



Products with length less than or equal to 5:

0       iPhone

3         iPad

dtype: object

Code analysis:

Example 4: Analyzing Length Distribution

len() It can be used for statistical analysis.

Example

import

pandas

as

pd

Create a Series containing sentence lengths

sentences

=

pd.

Series

(

[

   

'Hello'

,

   

'Hello world'

,

   

'Pandas is powerful'

,

   

'Data science with machine learning'

,

   

'AI'

]

)

Compute the length of each sentence

lengths

=

sentences.

str

.

len

(

)

print

(

"Sentence list:"

)

print

(

sentences

)

print

(

"nCharacter length of each sentence:"

)

print

(

lengths

)

print

(

"nStatistics:"

)

print

(

f

"Shortest length: {lengths.min()}"

)

print

(

f

"Longest length: {lengths.max()}"

)

print

(

f

"Average length: {lengths.mean():.2f}"

)

print

(

f

"Total length: {lengths.sum()}"

)

Output result:



Sentence list:

0                            Hello

1                       Hello world

2                  Pandas is powerful

3    Data science with machine learning

4                             AI

dtype: object



Character length of each sentence:

0      5

1     11

2     18

3     29

4      2

dtype: int64



Statistics:

最短长度: 2

最长长度: 29

平均长度: 13.00

总长度: 65

Code analysis:

Example 5: Handling Mixed-Type Data

len() It also computes the string representation length of non-string elements such as numbers.

Example

import

pandas

as

pd

import

numpy

as

np

Create a Series containing mixed types

s

=

pd.

Series

(

[

'hello'

,

12345

,

'runoob'

,

np.

nan

,

'py'

]

)

Compute lengths

result

=

s.

str

.

len

(

)

print

(

"Original Series:"

)

print

(

s

)

print

(

"nString lengths:"

)

print

(

result

)

Output result:



原始 Series:

0       hello

1       12345

2      runoob

3        NaN

4         py

dtype: object



String length:

0       5.0

1       5.0

2       6.0

3       NaN

4       2.0

Code analysis:

Example 6: Counting Words with split

You can think of len() The difference between split() Combine with it to count words.

Example

import

pandas

as

pd

Create a Series containing sentences

sentences

=

pd.

Series

(

[

   

'hello world'

,

   

'runoob python tutorial'

,

   

'pandas data analysis'

,

   

'machine learning'

]

)

Split first, then compute lengths to get the word count

word_counts

=

sentences.

str

.

split

(

)

.

str

.

len

(

)

print

(

"Sentence list:"

)

print

(

sentences

)

print

(

"nWord counts:"

)

print

(

word_counts

)

Output result:



Sentence list:

0           hello world

1    runoob python tutorial

2    pandas data analysis

3    machine learning

dtype: object



Word count:

0    2

1    3

2    3

3    2

dtype: int64

Code analysis:


Notes


Pandas Common Functions Common Pandas functions