Pandas Series.str_len() function
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
- Parameters: No parameters. This function requires no arguments and can be called directly.
Function description
- Return Value: Returns an integer Series representing the character count of each string.
- effect: Computes the character count of each string element in the Series (including spaces and special characters).
- Note: For non-string elements, returns the length of their string representation.
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
(
)
(
"Original Series:"
)
(
s
)
(
"nString lengths:"
)
(
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:
s.str.len()Computes the character count of each string.- 'hello' has 5 characters, returning 5.
- 'runoob' has 6 characters, returning 6.
- 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
(
)
(
"Original Series:"
)
(
s
)
(
"nString lengths (including spaces):"
)
(
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:
- 'hello world' has 11 characters (including the space in the middle).
- ' space ' has 8 characters (including two spaces at each end).
- Spaces are counted as characters.
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:"
;
)
(
products
)
(
"
;
nLength greater than
8
products:"
;
)
(
long_names
)
(
"
;
nLength less than or equal to
5
products:"
;
)
(
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:
products.str.len() > 8Returns a boolean Series indicating whether the length is greater than 8.- Use boolean indexing to filter out the qualifying product names.
- This is a common data filtering operation.
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
(
)
(
"Sentence list:"
)
(
sentences
)
(
"nCharacter length of each sentence:"
)
(
lengths
)
(
"nStatistics:"
)
(
f
"Shortest length: {lengths.min()}"
)
(
f
"Longest length: {lengths.max()}"
)
(
f
"Average length: {lengths.mean():.2f}"
)
(
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:
lengths.min()Returns the shortest string length.lengths.max()Returns the longest string length.lengths.mean()Returns the average length.lengths.sum()Returns the total character count.
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
(
)
(
"Original Series:"
)
(
s
)
(
"nString lengths:"
)
(
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:
- The number 12345 is converted to the string '12345', with a length of 5.
- NaN values return NaN (no error is raised).
- The result is of type float because NaN is a float.
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
(
)
(
"Sentence list:"
)
(
sentences
)
(
"nWord counts:"
)
(
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:
str.split()Splits sentences into lists of words..str.len()Computes the length of the list (i.e., the word count).- This is very useful when counting words in text.
Notes
str.len()It counts characters, not bytes.- For Chinese characters, each Han character counts as one character.
- Special characters such as spaces and tabs are also counted.
- If the Series contains NaN values, NaN is returned (instead of raising an error).
- For non-string elements (such as numbers), they are converted to strings before computing the length.
- This function returns a new Series and does not modify the original data.
Common Pandas functions