如何将DataFrame转换为含复合键的字典,避免值被覆盖
问题描述
我有如下所示的DataFrame:
col1 col2 col3 col4 action_id 0 1 2 2 0 a, apple 1 1 2 3 5 b, apple 2 0.2 0.3 8 1 c, apple 3 0.2 0.02 1 2 a, apple 4 11 11 22 11 b, apple
我希望将该DataFrame转换为以action_id为键、其余列为值的字典,期望输出格式如下:
{(1, 'a', 'apple'): array([[1, 2, 2, 0]]), (1, 'b', 'apple'): array([[1, 2, 3, 5]]), (1, 'c', 'apple'): array([[0.2, 0.3, 8, 1]]), (2, 'a', 'apple'): array([[0.2, 0.02, 1, 2]]), (2, 'b', 'apple'): array([[11, 11, 22, 11]])}
我尝试了以下方法(其中var为该DataFrame变量):
data2d = var.set_index('action_id').T.to_dict('list')
但该方法会覆盖重复键对应的值,仅返回重复键的最后一个值,结果如下:
{('c', 'apple'): array([[0.2, 0.3, 8, 1]]), ('a', 'apple'): array([[0.2, 0.02, 1, 2]]), ('b', 'apple'): array([[11, 11, 22, 11]])}
请问有没有办法保留含不同值的重复键?
编辑内容
我对action_id列做了修改,新增了一个元素,修改后的DataFrame如下:
col1 col2 col3 col4 action_id 0 1 2 2 0 1, a, apple 1 1 2 3 5 1, b, apple 2 0.2 0.3 8 1 1, c, apple 3 0.2 0.02 1 2 2, a, apple 4 11 11 22 11 2, b, apple
但仍然遇到相同的问题,仅返回最后一个值:
{(1, 'c', 'apple'): array([[0.2, 0.3, 8, 1]]), (2, 'a', 'apple'): array([[0.2, 0.02, 1, 2]]), (2, 'b', 'apple'): array([[11, 11, 22, 11]])}
解决方案
方法一:分组后手动构建字典
先把action_id列拆成唯一的元组键,再按分组提取对应数据转成数组,最后组装成字典:
import pandas as pd import numpy as np # 处理action_id列,转为带类型的元组(第一个元素转int,其余转字符串) var['action_id'] = var['action_id'].apply( lambda x: tuple( int(item.strip()) if i == 0 else item.strip() for i, item in enumerate(x.split(',')) ) ) # 分组构建目标字典 result = {} for key, group in var.groupby('action_id'): # 提取非action_id列,转为二维数组 result[key] = group.drop('action_id', axis=1).values.reshape(1, -1)
方法二:用分组聚合+to_dict简化实现
和方法一逻辑一致,用聚合函数直接把每组数据转成数组,再转字典:
import pandas as pd import numpy as np # 先处理action_id列 var['action_id'] = var['action_id'].apply( lambda x: tuple( int(item.strip()) if i == 0 else item.strip() for i, item in enumerate(x.split(',')) ) ) # 分组聚合后转字典 result = var.groupby('action_id').agg( lambda x: np.array(x).reshape(1, -1) ).to_dict('index')
原方法失效原因
set_index('action_id')要求索引唯一,虽然重复索引不会报错,但后续转字典时会自动保留最后一条重复索引对应的值,这就是出现覆盖问题的核心原因。
内容的提问来源于stack exchange,提问作者Ninad Kulkarni
相关产品推荐
相关产品推荐

