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

如何按值的索引位置拆分Pandas DataFrame列

Pandas拆分列:提取首字符与剩余部分

构造示例数据

先还原你的初始DataFrame:

import pandas as pd

df = pd.DataFrame({'variable': ['m4', 'm410', 'f1115']})

方法1:使用字符串切片str.slice

直接通过切片定位字符位置拆分:

# 提取第一个字符作为col1
df['col1'] = df['variable'].str.slice(0, 1)
# 提取从第2个字符开始的剩余内容作为col2
df['col2'] = df['variable'].str.slice(1)

方法2:使用正则提取str.extract

通过正则表达式一次性捕获首字符和剩余部分,代码更简洁:

# 正则规则:^匹配开头,(\w)捕获首字符,(.*)捕获剩余所有内容
df[['col1', 'col2']] = df['variable'].str.extract(r'^(\w)(.*)$')

最终结果

执行上述任意方法后,DataFrame会变为:

variablecol1col2
m4m4
m410m410
f1115f1115

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 00:25:21