python pandas文本连接

文本连接
方法s.str.cat()具有文本连接的功能,可以将序列连接成一个文本或者将两个文本序列连接在一起。
# 文本序列
s = pd.Series(['x', 'y', 'z'], dtype="string")
# 默认无符号连接
s.str.cat()
# 'xyz'
# 用逗号连接
s.str.cat(sep=',')
# 'x,y,z'
如果序列中有空值,会默认忽略空值,也可以指定空值的占位符号:
# 包含空值的文本序列
t = pd.Series(['h', 'i', np.nan, 'k'], dtype="string")
# 用逗号连接
t.str.cat(sep=',')
# 'h,i,k'
# 用连字符
t.str.cat(sep=',', na_rep='-')
# 'h,i,-,k'
t.str.cat(sep=',', na_rep='j')
# 'h,i,j,k'
当然也可以使用pd.concat()来连接两个序列:
s
'''
0 x
1 y
2 z
dtype: string
'''
t
'''
0 h
1 i
2 <NA>
3 k
dtype: string
'''
# 连接
pd.concat([s, t], axis=1)
'''
0 1
0 x h
1 y i
2 z <NA>
3 <NA> k
'''
# 两次连接
s.str.cat(pd.concat([s, t], axis=1), na_rep='-')
'''
0 xxh
1 yyi
2 zzdtype: string
'''
连接的对齐方式:
h = pd.Series(['b', 'd', 'a'],
index=[1, 0, 2],
dtype="string")
# 以左边的索引为准
s.str.cat(h)
s.str.cat(t, join='left')
# 以右边的索引为准
s.str.cat(h, join='right')
# 其他
s.str.cat(h, join='outer', na_rep='-')
s.str.cat(h, join='inner', na_rep='-')

 

posted @ 2024-01-28 08:25  myrj  阅读(24)  评论(0编辑  收藏  举报