python中split函数_python pandas Series.str.split用法及代码示例

在给定的分隔符/定界符周围拆分字符串。

从开头的指定定界符字符串处分割Series /Index中的字符串。相当于str.split()。

参数:

pat:str, 可选参数要分割的字符串或正则表达式。如果未指定,请在空白处分割。

n:int, 默认为 -1 (all)限制输出的分割数。None,则0和-1将被解释为返回所有拆分。

expand:bool, 默认为 False将拆分的字符串展开为单独的列。

如果True,返回DataFrame /MultiIndex扩展维。

如果False,返回包含字符串列表的Series /Index。

返回值:

Series类型匹配调用者,除非expand=True(请参阅注释)。

注意:

的处理n关键字取决于找到的分割数:

如果发现分裂>n,先做n仅拆分

如果发现分裂<=n,进行所有拆分

如果对于某行,找到的分割数

如果使用expand=True, Series 和索引调用者分别返回DataFrame和MultiIndex对象。

例子:

>>> s = pd.Series(["this is a regular sentence",

... "https://docs.python.org/3/tutorial/index.html",

... np.nan])

0 this is a regular sentence

1 https://docs.python.org/3/tutorial/index.html

2 NaN

dtype:object

在默认设置中,字符串由空格分隔。

>>> s.str.split()

0 [this, is, a, regular, sentence]

1 [https://docs.python.org/3/tutorial/index.html]

2 NaN

dtype:object

没有n参数,输出rsplit和split一样

>>> s.str.rsplit()

0 [this, is, a, regular, sentence]

1 [https://docs.python.org/3/tutorial/index.html]

2 NaN

dtype:object

的n参数可用于限制定界符上的分割数。输出split和rsplit是不同的。

>>> s.str.split(n=2)

0 [this, is, a regular sentence]

1 [https://docs.python.org/3/tutorial/index.html]

2 NaN

dtype:object

>>> s.str.rsplit(n=2)

0 [this is a, regular, sentence]

1 [https://docs.python.org/3/tutorial/index.html]

2 NaN

dtype:object

的pat参数可用于按其他字符分割。

>>> s.str.split(pat = "/")

0 [this is a regular sentence]

1 [https:, , docs.python.org, 3, tutorial, index...

2 NaN

dtype:object

使用时expand=True,拆分后的元素将展开为单独的列。如果存在NaN,它将在拆分过程中传播到整个列中。

>>> s.str.split(expand=True)

0 1 2 3

0 this is a regular

1 https://docs.python.org/3/tutorial/index.html None None None

2 NaN NaN NaN NaN \

4

0 sentence

1 None

2 NaN

对于稍微复杂的用例,例如从url拆分html文档名称,可以使用参数设置的组合。

>>> s.str.rsplit("/", n=1, expand=True)

0 1

0 this is a regular sentence None

1 https://docs.python.org/3/tutorial index.html

2 NaN NaN

当显式使用正则表达式时,请记住转义特殊字符。

>>> s = pd.Series(["1+1=2"])

>>> s.str.split(r"\+|=", expand=True)

0 1 2

0 1 1 2

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值