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

如何用两个列表在Python中生成指定字典与DataFrame?

需求与实现方案

输入数据

L1 = ['a','b','c','a','b','c']
L2 = ['Cat','Fish','Crow','Dog','Frog','Eagle']

目标输出

  1. 分组字典:
D1 = {'a':['Cat','Dog'],
      'b':['Fish','Frog'],
      'c':['Crow','Eagle']}
  1. 指定结构的DataFrame:
ABC
CatFishCrow
DogFrogEagle

实现代码

1. 生成分组字典

两种方式均可适配任意数量的分组键:

# 方法1:基础循环构建
L1 = ['a','b','c','a','b','c']
L2 = ['Cat','Fish','Crow','Dog','Frog','Eagle']

D1 = {}
for key, val in zip(L1, L2):
    if key not in D1:
        D1[key] = []
    D1[key].append(val)
# 方法2:用collections.defaultdict简化代码
from collections import defaultdict

L1 = ['a','b','c','a','b','c']
L2 = ['Cat','Fish','Crow','Dog','Frog','Eagle']

D1 = defaultdict(list)
for key, val in zip(L1, L2):
    D1[key].append(val)
# 若需转为普通字典,执行:D1 = dict(D1)

2. 生成指定结构的DataFrame

自动适配100+列的场景,无需手动定义列名:

import pandas as pd

# 基于已生成的分组字典D1构建DataFrame,列名转为大写
DF1 = pd.DataFrame({key.upper(): values for key, values in D1.items()})

执行后得到的DataFrame结构与目标完全一致,列名自动根据分组键生成,行对应各分组下的所有值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 08:25:20