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

如何将值为数字列表的字典转换为指定格式的Pandas DataFrame?

实现方法

当然有,分三步就能快速实现:

  1. 定义尺寸数字到别名的映射:根据示例规则,先把数字对应到sml/med/lrg:
    size_map = {28: 'sml', 30: 'med', 32: 'lrg', 34: 'lrg', 38: 'lrg'}
    
  2. 反转字典,收集每个数字对应的颜色:
    from collections import defaultdict
    num_colors = defaultdict(list)
    for color, nums in opt.items():
        for num in nums:
            num_colors[num].append(color)
    
  3. 按尺寸别名聚合,转成DataFrame:
    import pandas as pd
    size_colors = defaultdict(list)
    for num, colors in num_colors.items():
        size = size_map[num]
        # 去重并保留首次出现的顺序
        unique_colors = list(dict.fromkeys(colors))
        size_colors[size].extend(unique_colors)
    # 对每个尺寸下的颜色再次去重
    for size in size_colors:
        size_colors[size] = list(dict.fromkeys(size_colors[size]))
    # 生成DataFrame
    df = pd.DataFrame(size_colors.items(), columns=['size', 'color'])
    

运行后就能得到你要的结构,要是需要调整尺寸映射规则,直接修改size_map就行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 06:15:20