Pandas Series.str.cat() 方法



Pandas 中的Series.str.cat()方法用於連線 Series 或 Index 中的字串,並使用給定的分隔符。此方法可以將 Series/Index 與來自另一個 Series、Index、DataFrame、NumPy 陣列或列表狀物件的元素連線起來。如果未指定其他元素,則會使用給定的分隔符將 Series/Index 中的所有值連線成單個字串。

語法

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

Series.str.cat(others=None, sep=None, na_rep=None, join='left')

引數

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

  • others - Series、Index、DataFrame、np.ndarray 或列表狀物件,將與呼叫的 Series/Index 連線。它們必須與呼叫的 Series/Index 具有相同的長度,除了當 join 不為 None 時索引物件。

  • sep - 連線元素之間使用的分隔符。預設為空字串 ''。

  • na_rep - 缺失值的表示形式。如果為 None,則如果 others 為 None,則省略缺失值,否則在連線之前任何列中具有缺失值的行的結果將具有缺失值。

  • join - 指定呼叫 Series/Index 與 others 中的任何 Series/Index/DataFrame 之間的連線樣式。選項包括 {'left', 'right', 'outer', 'inner'}。預設為 'left'。

返回值

如果others 為 None,則Series.str.cat()方法返回連線的字串。否則,它返回連線物件的 Series/Index(與呼叫者相同型別)。

示例 1

這是一個使用Series.str.cat()方法將所有值連線成單個字串的基本示例。

import pandas as pd
import numpy as np

# Create a Series
s = pd.Series(['a', 'b', np.nan, 'd'])
print('Input Series:')
print(s)

# Concatenate without 'others'
result = s.str.cat()
print("Output:",result)

以上程式碼的輸出如下:

Input Series:
0      a
1      b
2    NaN
3      d
dtype: object

Output: abd

示例 2

此示例使用 "na_rep" 引數用給定的表示形式替換缺失值。

import pandas as pd
import numpy as np

# Create a Series
s = pd.Series(['a', 'b', np.nan, 'd'])
print('Input Series:')
print(s)

# Concatenate with na_rep
result = s.str.cat(sep=' ', na_rep='?')
print("Output:",result)

以上程式碼的輸出如下:

'a b ? d'

示例 3

此示例將輸入 Series 與 "others" 物件連線。

import pandas as pd
import numpy as np

# Create a Series
s = pd.Series(['a', 'b', np.nan, 'd'])
print('Input Series:')
print(s)

# Concatenate with 'others'
result = s.str.cat(['A', 'B', 'C', 'D'], sep=',')
print("Output:",result)

以上程式碼的輸出如下:

Input Series:
0      a
1      b
2    NaN
3      d
dtype: object

Output: 
0    a,A
1    b,B
2    NaN
3    d,D
dtype: object

示例 4

以下示例演示瞭如何使用 "join" 關鍵字連線兩個具有不同索引的 Series。

import pandas as pd
import numpy as np

# Create Series with different indexes
s = pd.Series(['a', 'b', np.nan, 'd'])
t = pd.Series(['d', 'a', 'e', 'c'], index=[3, 0, 4, 2])

# Concatenate with 'join=left'
result_left = s.str.cat(t, join='left', na_rep='-')
print(result_left)

# Concatenate with 'join=outer'
result_outer = s.str.cat(t, join='outer', na_rep='-')
print(result_outer)

# Concatenate with 'join=inner'
result_inner = s.str.cat(t, join='inner', na_rep='-')
print(result_inner)

# Concatenate with 'join=right'
result_right = s.str.cat(t, join='right', na_rep='-')
print(result_right)

以上程式碼的輸出如下:

join='left':
0    aa
1    b-
2    -c
3    dd
dtype: object
join='outer':
0 aa
1 b-
2 -c
3 dd
4 -e
dtype: object

join='inner':
0 aa
2 -c
3 dd
dtype: object

join='right':
3 dd
0 aa
4 -e
2 -c
dtype: object

示例 5

讓我們再看一個示例,演示Series.str.cat()方法在 Pandas DataFrame 列上的工作原理。

import pandas as pd

# Read the data into a DataFrame
data = {'Name': ['John', 'Jane', 'Alice'],
'Surname': ['Doe', 'Smith', 'Johnson']}
df = pd.DataFrame(data)

# Display the input DataFrame
print("Original DataFrame:")
print(df)

# Join the columns
df['Full Name'] = df['Name'].str.cat(df['Surname'], sep=' ')

# Display the joined data
print('Output Modified DataFrame:')
print(df)

當我們執行以上程式時,它會產生以下結果:

Original DataFrame:
    Name  Surname
0   John      Doe
1   Jane    Smith
2  Alice  Johnson
Output Modified DataFrame:
Name Surname Full Name
0 John Doe John Doe
1 Jane Smith Jane Smith
2 Alice Johnson Alice Johnson
python_pandas_working_with_text_data.htm
廣告