一、介紹
數據預處理時,有時需要將數據字段進行合並拼接,可以使用 str.cat()
方法實現。
- 使用語法
Series.str.cat(others=None, sep=None, na_rep=None, join='left')
- 參數說明
others -- 如果給定,則對應位置拼接;如果不給定,則拼接自身為字符串
sep -- 連接符、分割符,默認空格
na_rep -- 缺失值
join -- 拼接方式
二、實操
1.構建測試集
import pandas as pd
import numpy as np
df = pd.DataFrame({'user_id':['A','B','C','D','E'],
'v0':['high','tall','high','one','two'],
'v1':np.random.rand(5),
'v2':np.random.rand(5),
'v3':np.random.rand(5),
'v4':np.random.rand(5),
'v5':np.random.rand(5)})
'''
user_id v0 v1 v2 v3 v4 v5
0 A high 0.269505 0.123080 0.366477 0.529162 0.683024
1 B tall 0.620859 0.469152 0.039121 0.221539 0.665314
2 C high 0.657277 0.787288 0.488835 0.690670 0.029768
3 D one 0.648150 0.234147 0.841002 0.403383 0.313004
4 E two 0.532817 0.246520 0.277159 0.946502 0.369891
'''
2.拼接兩列
# 字符串類型
df['user_id'].str.cat(df['v0'])
# 添加連接符
df['user_id'].str.cat(df['v0'], sep=' -- ')
'''
0 A -- high
1 B -- tall
2 C -- high
3 D -- one
4 E -- two
'''
3.數值列合並
str.cat
方法合並的列內容必須都是字符串,如果是數值型會報錯,需要提前轉換為字符類型。
# 類型錯誤
df['user_id'].str.cat(df['v1'], sep=' -- ')
# TypeError: Concatenation requires list-likes containing only strings (or missing values). Offending values found in column floating
# 類型轉換
df['v1'] = df['v1'].map(lambda x: str(x))
df['user_id'].str.cat(df['v1'], sep=' -- ')
'''
0 A -- 0.26950510515647086
1 B -- 0.6208590675841862
2 C -- 0.657277409259944
3 D -- 0.6481499976765789
4 E -- 0.5328165450111593
Name: user_id, dtype: object
'''
# 使用astype轉換
df['user_id'].str.cat(df['v2'].astype('str'), sep=' -- ')
4.拼接特定字符串
舉個例子:想要某列添加單位(萬元),該如何實現?
# 報錯
df['v1'].str.cat('萬元')
# ValueError: Did you mean to supply a `sep` keyword?
# 方法一(不建議):構造輔助列,再進行合並
df['add_columns'] = '萬元'
df['v1'].str.cat(df['add_columns'], sep='-')
'''
0 0.26950510515647086-萬元
1 0.6208590675841862-萬元
2 0.657277409259944-萬元
3 0.6481499976765789-萬元
4 0.5328165450111593-萬元
Name: v1, dtype: object
'''
# 方法二:直接“+”解決
df['v1'] + '-萬元'
但需注意,方法二遇到缺失值會報錯,需提前進行缺失值填充。
5.多列拼接
多列拼接時,需要用中括號將多列括起來。
df['user_id'].str.cat([df['v0'], df['v1'], df['add_columns']], sep='-')
'''
0 A-high-0.26950510515647086-萬元
1 B-tall-0.6208590675841862-萬元
2 C-high-0.657277409259944-萬元
3 D-one-0.6481499976765789-萬元
4 E-two-0.5328165450111593-萬元
Name: user_id, dtype: object
'''
6.不指定others參數
# 默認
s = pd.Series(['a', 'b', np.nan, 'd'])
s.str.cat(sep='-') # 'a-b-d'
# 指定缺失值
s.str.cat(sep='-', na_rep='???') # 'a-b-???-d'
7.索引對齊方式
s = pd.Series(['a', 'b', np.nan, 'd'])
t = pd.Series(['d', 'a', 'e', 'c'], index=[3, 0, 4, 2])
# 按照索引左拼接
s.str.cat(t, join='left', na_rep='-')
# 外拼接
s.str.cat(t, join='outer', na_rep='-')
# 內拼接
s.str.cat(t, join='inner', na_rep='-')
## 如果不指定 na_rep 缺失值 則拼接出來內容為 NaN
# 右拼接
s.str.cat(t, join='right', na_rep='-')