pandas
文本
连接
看过来
《pandas 教程》 持续更新中,可作为 pandas 入门进阶课程、pandas 中文手册、用法大全,配有案例讲解和速查手册。提供建议、纠错、催更等加作者微信: gairuo123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。查看更新日志。作者开办 Python 数据分析训练营正在报名中,详情 Python 数据分析训练营。
![]() |
本教程作者所著新书《Python之光:Python编程入门与实战》(ISBN:9787111729891)已由机械工业出版社出版上市,各大电商平台有售,欢迎:查看详情并关注购买。 |
![]() |
本教程作者所著新书《深入浅出Pandas:利用Python进行数据处理与分析》(ISBN:9787111685456)已由机械工业出版社出版上市,各大电商平台有售,欢迎:查看详情并关注购买。 |
方法 s.str.cat 可以做文本连接的功能,本文介绍如何将序列的文本或者两个文本序列连接在一起的方法。
s = pd.Series(['a', 'b', 'c', 'd'], dtype="string")
s.str.cat(sep=',')
# 'a,b,c,d'
s.str.cat()
# 'abcd'
对空值的处理:
t = pd.Series(['a', 'b', np.nan, 'd'], dtype="string")
t.str.cat(sep=',')
#'a,b,d'
t.str.cat(sep=',', na_rep='-')
# 'a,b,-,d'
s.str.cat(['A', 'B', 'C', 'D'])
'''
0 aA
1 bB
2 cC
3 dD
dtype: string
'''
对空值的处理:
s.str.cat(t)
'''
0 aa
1 bb
2 <NA>
3 dd
dtype: string
'''
s.str.cat(t, na_rep='-')
'''
0 aa
1 bb
2 c-
3 dd
dtype: string
'''
当然我们也可以使用 pd.concat
来进行链接两个序列:
d = pd.concat([t, s], axis=1)
# 两次连接
s.str.cat(d, na_rep='-')
连接的对齐方式:
u = pd.Series(['b', 'd', 'a', 'c'],
index=[1, 3, 0, 2],
dtype="string")
# 以左边索的为主
s.str.cat(u)
s.str.cat(u, join='left')
# 以右边的索引为主
s.str.cat(u, join='right')
# 其他
s.str.cat(t, join='outer', na_rep='-')
s.str.cat(t, join='inner', na_rep='-')
无「盖若」授权,请勿以任何形式转载,公众号:gairuo
Copyright © 2019 - 2023
Gairuo.com All Rights Reserved v7.6.1.0919
京公网安备11010502033395号
京ICP备15019454号-4