Pandas Series.str.len() 方法



Python Pandas 庫中的Series.str.len()方法用於計算 Series 或 Index 中每個元素的長度。這些元素可以是序列,例如字串、元組或列表,也可以是集合,例如字典。

此方法對於文字資料處理和分析特別有用,因為它允許您快速有效地計算 Series 中元素的大小或長度。

語法

以下是 Pandas Series.str.len()方法的語法

Series.str.len()

引數

Series.str.len()方法不接受任何引數。

返回值

Series.str.len()方法返回一個整數型別的 Series 或 Index。每個整數值表示原始 Series 或 Index 中對應元素的長度。

示例 1

此示例演示了Series.str.len()方法的基本用法,用於計算 Series 中字串元素的長度。

import pandas as pd

# Create a Series of strings
series = pd.Series(["Foo", "bar", "London", "Quarantine"])
print("Series: \n", series)

# Compute the length of each string element
length = series.str.len()
print("Length:\n", length)

當我們執行上述程式碼時,它會生成以下輸出

Series: 
 0           Foo
1           bar
2        London
3    Quarantine
dtype: object
Length:
 0    3
1    3
2    6
3    10
dtype: int64

示例 2

此示例演示了包含不同型別元素的 Series 的Series.str.len()方法,包括字串、空字串、整數、字典、列表和元組。

import pandas as pd

# Create a Series with various types of elements
s = pd.Series(['panda', '', 5, {'language': 'Python'}, [2, 3, 5, 7], ('one', 'two', 'three')])
print("Original Series: \n", s)

# Compute the length of each element
length = s.str.len()

print("Output Length of each element in the Series:\n", length)

當我們執行上述程式碼時,它會生成以下輸出

Original Series: 
 0                     panda
1                          
2                         5
3    {'language': 'Python'}
4              [2, 3, 5, 7]
5         (one, two, three)
dtype: object

Output Length of each element in the Series:
 0    5.0
1    0.0
2    NaN
3    1.0
4    4.0
5    3.0
dtype: float64

示例 3

此示例演示了在包含列表的 DataFrame 列中使用Series.str.len()方法。計算每個列表的長度並將其儲存在新列中。

import pandas as pd

# Create a DataFrame with a column of lists
df = pd.DataFrame({"A": [[1, 2, 3], [0, 1, 3]], "B": ['Tutorial', 'AEIOU']})

print("Original DataFrame:")
print(df)

# Compute the length of each element in column 'B'
df['C'] = df['B'].str.len()

print("\nDataFrame after computing the length of elements in column 'B':")
print(df)

當我們執行上述程式碼時,它會生成以下輸出

Original DataFrame:
           A         B
0  [1, 2, 3]  Tutorial
1  [0, 1, 3]     AEIOU

DataFrame after computing the length of elements in column 'B':
           A         B  C
0  [1, 2, 3]  Tutorial  8
1  [0, 1, 3]     AEIOU  5
廣告