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

使用Python3.8+Pandas1.1.4拆分DataFrame字母数字组合列

解决方案:拆分Pandas DataFrame的combination列

嗨,这个需求很好实现,针对你使用的Python 3.8和Pandas 1.1.4版本,我给你两种实用的方案:

方案一:指定正则捕获组(适合字段固定的场景)

这种方法适合你已经明确知道所有需要拆分的字母列(A、B、C、R...L)的情况,直接通过正则捕获组提取对应内容:

import pandas as pd

# 初始化你的DataFrame(替换成你实际的df)
df = pd.DataFrame({
    'id': [1,2,3],
    'combination': [
        'A23B14C02R01D05E03F07G07H01I00J02K11L30',
        'A11B14C02R01D05E03F07G07H01I00J02K11L30',
        'A30B14C02R01D05E03F07G07H01I00J02K11L30'
    ]
})

# 定义正则模式,每个(?P<列名>)是一个捕获组,对应字母加两位数字
pattern = r'(?P<A>A\d{2})(?P<B>B\d{2})(?P<C>C\d{2})(?P<R>R\d{2})(?P<D>D\d{2})(?P<E>E\d{2})(?P<F>F\d{2})(?P<G>G\d{2})(?P<H>H\d{2})(?P<I>I\d{2})(?P<J>J\d{2})(?P<K>K\d{2})(?P<L>L\d{2})'

# 提取所有捕获组的数据
extracted_cols = df['combination'].str.extract(pattern)

# 移除每个列值的前缀字母,只保留数字部分
for col in extracted_cols.columns:
    extracted_cols[col] = extracted_cols[col].str[1:]

# 合并原id列和拆分后的列
final_df = pd.concat([df['id'], extracted_cols], axis=1)

print(final_df)

方案二:动态提取(适合字段可能变化的场景)

如果后续combination的字段格式不变(字母+两位数字)但字段数量可能调整,用这种动态提取的方法更灵活,不需要手动写每个捕获组:

import pandas as pd

df = pd.DataFrame({
    'id': [1,2,3],
    'combination': [
        'A23B14C02R01D05E03F07G07H01I00J02K11L30',
        'A11B14C02R01D05E03F07G07H01I00J02K11L30',
        'A30B14C02R01D05E03F07G07H01I00J02K11L30'
    ]
})

# 提取所有"字母+两位数字"的组合,拆分成字母和数字两部分
extracted = df['combination'].str.extractall(r'([A-Z])(\d{2})')

# 设置列名,然后通过pivot把字母转成列,数字作为对应值
extracted.columns = ['letter', 'value']
extracted_pivot = extracted.reset_index().pivot(index='level_0', columns='letter', values='value')

# 合并原id列,level_0对应原DataFrame的行索引
final_df = pd.concat([df['id'], extracted_pivot], axis=1)

# 调整列顺序和你期望的一致(可选)
final_df = final_df[['id', 'A', 'B', 'C', 'R', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']]

print(final_df)

两种方法都能得到你想要的输出格式,而且完全兼容Pandas 1.1.4版本,你可以根据自己的场景选择合适的方案~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:33:56