pandas.Series.str.rsplit#
- Series.str.rsplit(pat=None, *, n=-1, expand=False)[source]#
在給定分隔符/定界符周圍分割字串。
從末尾分割 Series/Index 中的字串,使用指定的分隔符字串。
- 引數:
- patstr, optional
用於分割的字串。如果未指定,則按空格分割。
- nint,預設為 -1(全部)
限制輸出中的分割次數。
None、0 和 -1 將被解釋為返回所有分割。- expandbool, default False
將分割後的字串展開為單獨的列。
如果為
True,則返回 DataFrame/MultiIndex,擴充套件維度。如果為
False,則返回 Series/Index,其中包含字串列表。
- 返回:
- Series, Index, DataFrame 或 MultiIndex
型別匹配呼叫者,除非
expand=True(請參閱 Notes)。
另請參閱
Series.str.split在給定分隔符/定界符周圍分割字串。
Series.str.rsplit從右側開始,圍繞給定的分隔符/定界符分割字串。
Series.str.join使用傳入的分隔符連線 Series/Index 中包含的列表。
str.split標準庫版本用於 split。
str.rsplit標準庫版本用於 rsplit。
注意
對 n 關鍵字的處理取決於找到的分割數量
如果找到的分割數 > n,則只進行前 n 次分割
如果找到的分割數 <= n,則進行所有分割
如果對於某個行找到的分割數 < n,則在
expand=True時,會用None進行填充,直到達到 n。
如果使用
expand=True,Series 和 Index 呼叫者將分別返回 DataFrame 和 MultiIndex 物件。示例
>>> s = pd.Series( ... [ ... "this is a regular sentence", ... "https://docs.python.club.tw/3/tutorial/index.html", ... np.nan, ... ] ... ) >>> s 0 this is a regular sentence 1 https://docs.python.club.tw/3/tutorial/index.html 2 NaN dtype: str
在預設設定下,字串按空格分割。
>>> s.str.split() 0 [this, is, a, regular, sentence] 1 [https://docs.python.club.tw/3/tutorial/index.html] 2 NaN dtype: object
如果不使用 n 引數,rsplit 和 split 的輸出是相同的。
>>> s.str.rsplit() 0 [this, is, a, regular, sentence] 1 [https://docs.python.club.tw/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.club.tw/3/tutorial/index.html] 2 NaN dtype: object
>>> s.str.rsplit(n=2) 0 [this is a, regular, sentence] 1 [https://docs.python.club.tw/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.club.tw/3/tutorial/index.html NaN NaN NaN NaN 2 NaN NaN NaN NaN NaN
對於更復雜的用例,例如從 URL 中分割 HTML 文件名,可以使用引數設定的組合。
>>> s.str.rsplit("/", n=1, expand=True) 0 1 0 this is a regular sentence NaN 1 https://docs.python.club.tw/3/tutorial index.html 2 NaN NaN