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

如何将含共同键的列表值合并为字典并应用于DataFrame

解决方法:将对话列表按用户分组并转换为字典(批量应用于DataFrame)

需求说明

我们需要处理交替存储用户名与对话内容的列表,将同一用户的所有对话合并为单个字符串,最终生成以用户名为键、合并后对话为值的字典;同时要将这个逻辑批量应用到包含多个此类列表的DataFrame中。

实现代码

def Convert(lst):
    dct = {}
    # 初始化所有用户名对应的空字符串键值对
    for ind in range(len(lst)):
        if ind % 2 == 0:
            if lst[ind] not in dct:
                dct[lst[ind]] = ""
    # 遍历对话内容,合并到对应用户名下
    for ind in range(len(lst)):
        if ind % 2 == 1:
            dct[lst[ind - 1]] += lst[ind] + " "
    # 移除每个对话字符串末尾多余的空格
    for key in dct:
        dct[key] = dct[key].strip()
    return dct

# 将转换逻辑应用到DataFrame的list_of_convo列
df['grouped'] = df['list_of_convo'].apply(Convert)

代码逻辑解释

  1. 初始化字典:遍历列表的偶数索引(对应用户名),为每个新出现的用户在字典中创建空字符串值的键
  2. 合并对话:遍历列表的奇数索引(对应对话内容),将当前对话追加到前一个索引对应的用户名下
  3. 优化格式:移除每个对话字符串末尾因拼接产生的多余空格

示例效果

处理后的DataFrame会新增grouped列,其中每行的结果为:

  • 行0:{'person1': 'Hi You there? Hru?', 'person2': 'Hello Good'}
  • 行1:{'person3': 'Hi You there? Hru?', 'person2': 'Hello Good'}
  • 行2:{'person5': 'Hi You there? Hru?', 'person2': 'Hello Good'}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:55:28