pandas.Series.str.rsplit#
- Series.str.rsplit(pat=None, *, n=-1, expand=False)[源代码]#
围绕给定分隔符拆分字符串。
从末尾在指定的分隔符字符串处拆分 Series/Index 中的字符串。
- Parameters:
- patbool, default False
用于拆分的字符串。如果未指定,则按空格拆分。
- nint,默认为 -1(全部)
限制输出中的拆分数。
None、0 和 -1 将被解释为返回所有拆分。- expandbool,默认 False
展开拆分的字符串到单独的列中。
如果为
True,则返回 DataFrame/MultiIndex,扩展维度。如果为
False,则返回 Series/Index,包含字符串列表。
- Returns:
- Series、Index、DataFrame 或 MultiIndex
除非 ``expand=True``(参见 Notes),否则类型与调用者匹配。
参见
Series.str.split围绕给定分隔符拆分字符串。
Series.str.rsplit从右侧围绕给定的分隔符/定界符拆分字符串。
Series.str.join使用分隔符连接 Series/Index 中作为元素的列表。
str.split用于拆分的标准库版本。
str.rsplit用于 rsplit 的标准库版本。
Notes
n 关键字的处理取决于找到的拆分数:
如果找到的拆分数 > n,则仅进行前 n 次拆分
如果找到的拆分数 <= n,则进行所有拆分
如果对于某个行找到的拆分数 < n,则在
expand=True的情况下追加 None 进行填充,直到达到 n
如果使用
expand=True,Series 和 Index 调用者分别返回 DataFrame 和 MultiIndex 对象。Examples
>>> s = pd.Series( ... [ ... "this is a regular sentence", ... "https://docs.python.org/3/tutorial/index.html", ... np.nan ... ] ... ) >>> s 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 4 0 this is a regular sentence 1 https://docs.python.org/3/tutorial/index.html None None None None 2 NaN NaN NaN NaN 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