Pandas Series.str.join() 方法



Pandas 中的Series.str.join()方法用於處理 Series/Index 或 DataFrame 列中的文字資料。此方法在處理 Series 元素中包含的列表時特別有用。

使用指定的定界符,Series.str.join() 方法允許您將這些列表的內容連線成單個字串。此操作等效於標準 Python str.join() 方法,但它是逐元素應用於 Series 中的每個條目。

語法

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

Series.str.join(sep)

引數

Series.str.join() 方法接受以下引數:

  • sep - 表示列表條目之間使用的分隔符的字串。

返回值

Series.str.join() 方法返回一個 Series 或 Index 物件,其中列表條目透過分隔符的中間出現連線起來。

引發異常

如果提供的 Series 不包含字串或列表,則該方法會引發AttributeError

注意:如果任何列表項不是字串物件,則連線的結果將為 NaN。

示例 1

此示例演示了使用Series.str.join()方法連線作為 Series 元素包含的列表。

import pandas as pd

# Create a Series of lists
s = pd.Series([['a', 'b', 'c'], ['1', '2', '3'], ['x', 'y', 'z']])

# Join the list entries with a comma delimiter
result = s.str.join(',')

print("Input Series:")
print(s)
print("\nJoined Strings:")
print(result)

執行以上程式碼後,將產生以下輸出:

Input Series:
0    [a, b, c]
1    [1, 2, 3]
2    [x, y, z]
dtype: object

Joined Strings:
0    a,b,c
1    1,2,3
2    x,y,z
dtype: object

示例 2

此示例演示了當 Series 中的元素不是列表時Series.str.join()方法的行為。

import pandas as pd

# Create a Series of strings
s = pd.Series(['apple', 'banana', 'cherry'])

# Attempt to join the string entries with a dash delimiter
result = s.str.join('-')

print("Joined Strings:")
print(result)

執行以上程式碼後,將產生以下輸出

Joined Strings:
0      a-p-p-l-e
1    b-a-n-a-n-a
2    c-h-e-r-r-y
dtype: object

因為 Series 中的元素不是列表,所以會引發AttributeError

示例 3

此示例演示了當列表包含非字串物件時Series.str.join()方法的行為。

import pandas as pd

# Create a Series of lists with non-string objects
s = pd.Series([['a', 'b', 'c'], [1, 2, 3], ['x', 'y', 'z']])

# Join the list entries with a comma delimiter
result = s.str.join(',')

print("Input Series:")
print(s)
print("\nJoined Strings:")
print(result)

執行以上程式碼後,將產生以下輸出:

Input Series:
0    [a, b, c]
1       [1, 2, 3]
2    [x, y, z]
dtype: object

Joined Strings:
0    a,b,c
1       NaN
2    x,y,z
dtype: object

NaN 值表示列表包含非字串物件。

python_pandas_working_with_text_data.htm
廣告