You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从右向左按分隔符拆分Pandas DataFrame中的列?

从右向左拆分DataFrame字符串列的解决方案

要实现从右向左按分隔符拆分DataFrame列,直接用Pandas的str.rsplit()方法即可——它和str.split()用法一致,但拆分方向是从字符串末尾开始。

针对示例字符串"hi.this.is.an.example",要得到"an"和"example"两列,只需把原代码里的split替换成rsplit,同时保留拆分次数参数:

df['variable'].str.rsplit('.', 2, expand=True)

细节说明:

  • rsplit('.', 2, expand=True)会从右侧开始,以.为分隔符最多拆分2次,最终得到3个部分:"hi.this.is"、"an"、"example"
  • 如果只需要最后两列,直接提取结果的对应列即可:
split_result = df['variable'].str.rsplit('.', 2, expand=True)
df[['target_col1', 'target_col2']] = split_result[[1, 2]]

内容的提问来源于stack exchange,提问作者user14736700

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 09:18:31