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

使用Pandas按多分隔符拆分DataFrame列生成新列

问题:拆分DataFrame的Summary列为分组命名列并填充默认值

原始DataFrame如下:

import pandas as pd

data = {
    'Area': ['M', 'M', 'M', 'M', 'H', 'H', 'H'],
    'DTTM': ['1/1/1960', '3/8/2021', '5/12/2024', '1/1/1960', '3/8/2021', '5/12/2024', '1/1/1960'],
    'ID': ['A', 'A', 'A', 'A', 'B', 'B', 'B'],
    'ID2': ['A', 'B', 'B', 'C', 'C', 'D', 'A'],
    'Summary': ['1:2980', '1:2980', '1:8732', '1:8732', '1:53174,9:2332', '1:22017,9:118', '1:4239, 6:184, 9:1243, 14:482']
}
df = pd.DataFrame(data)

需要将Summary列按group:value的格式拆分为以Bin{group}命名的新列,无对应数据的行填充0,最终得到目标格式。


解决方案

可以通过以下步骤实现:

  1. 解析Summary列生成字典
    先清理每个Summary字符串中的空格,再按逗号分割成每组,最后转成键为Bin{group}、值为对应数字的字典:

    def parse_summary(s):
        # 去除所有空格,按逗号分割各组
        groups = s.replace(' ', '').split(',')
        # 转成字典,键命名为Bin+分组号,值转为整数
        return {f'Bin{g.split(":")[0]}': int(g.split(":")[1]) for g in groups}
    
    # 生成字典列
    summary_dict = df['Summary'].apply(parse_summary)
    
  2. 将字典列拆分为多列
    使用pd.json_normalize把字典列展开成DataFrame:

    expanded_df = pd.json_normalize(summary_dict)
    
  3. 合并原DataFrame并填充默认值
    把展开后的DataFrame和原DataFrame合并,删除原Summary列,并用0填充缺失值,最后转为整数类型:

    result = pd.concat([df.drop('Summary', axis=1), expanded_df], axis=1)
    # 填充NaN为0,转整数
    result = result.fillna(0).astype(int)
    

完整代码
import pandas as pd

data = {
    'Area': ['M', 'M', 'M', 'M', 'H', 'H', 'H'],
    'DTTM': ['1/1/1960', '3/8/2021', '5/12/2024', '1/1/1960', '3/8/2021', '5/12/2024', '1/1/1960'],
    'ID': ['A', 'A', 'A', 'A', 'B', 'B', 'B'],
    'ID2': ['A', 'B', 'B', 'C', 'C', 'D', 'A'],
    'Summary': ['1:2980', '1:2980', '1:8732', '1:8732', '1:53174,9:2332', '1:22017,9:118', '1:4239, 6:184, 9:1243, 14:482']
}
df = pd.DataFrame(data)

def parse_summary(s):
    groups = s.replace(' ', '').split(',')
    return {f'Bin{g.split(":")[0]}': int(g.split(":")[1]) for g in groups}

summary_dict = df['Summary'].apply(parse_summary)
expanded_df = pd.json_normalize(summary_dict)

result = pd.concat([df.drop('Summary', axis=1), expanded_df], axis=1)
result = result.fillna(0).astype(int)

print(result)

运行后输出的结果和需求完全一致:

Area       DTTM ID ID2   Bin1  Bin6  Bin9  Bin14
0    M   1/1/1960  A   A   2980     0     0      0
1    M   3/8/2021  A   B   2980     0     0      0
2    M  5/12/2024  A   B   8732     0     0      0
3    M   1/1/1960  A   C   8732     0     0      0
4    H   3/8/2021  B   C  53174     0  2332      0
5    H  5/12/2024  B   D  22017     0   118      0
6    H   1/1/1960  B   A   4239   184  1243    482

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 08:20:19