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

如何在Pandas DataFrame中将Scope与其值拆分至新Type列并分行存储

Pandas拆分Scope列到多行并生成Type列

示例原数据

假设你的原始DataFrame结构如下:

import pandas as pd

df = pd.DataFrame({
    "ID": [1, 2],
    "Scope": ["Type1: 100; Type2: 200; Type3: 300", "Type1: 150; Type3: 250"]
})

解决步骤

  • 拆分Scope列并展开为多行:
    用str.split(';')把Scope的字符串按分号拆成列表,再通过explode()将列表元素转为独立行:

    df = df.assign(Scope=df['Scope'].str.split(';')).explode('Scope')
    
  • 拆分Type与对应值,生成新列:
    用str.split(':')拆分每行Scope的内容,扩展为两列后重命名,同时清理字符串两端的空格:

    df[['Type', 'Value']] = df['Scope'].str.split(':', expand=True).apply(lambda x: x.str.strip())
    
  • 整理列结构(可选):
    移除原Scope列,调整列顺序让结果更清晰:

    df = df.drop('Scope', axis=1)[['ID', 'Type', 'Value']]
    

最终结果

处理后的DataFrame如下:

ID   Type Value
0   1  Type1   100
0   1  Type2   200
0   1  Type3   300
1   2  Type1   150
1   2  Type3   250

如果你的Scope列格式有细微差异(比如分隔符不同),只需调整str.split()中的分隔符即可适配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 14:12:05