如何使用一个键将一个键到多个列表值的数据帧到python中的字典?

时间:2017-10-30 22:47:41

标签: python pandas dictionary dataframe pandas-groupby

我有一个像这样的数据框

ID    A    B    
1     3    5
1     4    2
1     0    4
2     2    1
2     4    5
2     9    3
3     2    1
3     4    6

我尝试使用代码将它们从stackoverflow中的其他帖子转换为

df.set_index('ID').T.to_dict('list')

但它给了我一个返回,每个ID只有一个列表值

{'1': [3,5], '2': [2,1], '3': [2,1]}

是否可以制作这样的字典?

{'1': ([3,5],[4,2],[0,4]), '2': ([2,1],[4,5],[9,3]), '3': ([2,1],[4,6])}

字典键返回ID,每个ID与元组列表组合,每个元组包含两个值。

2 个答案:

答案 0 :(得分:3)

In [150]: df.groupby('ID')['A','B'].apply(lambda x: x.values.tolist()).to_dict()
Out[150]:
{'1': [[3, 5], [4, 2], [0, 4]],
 '2': [[2, 1], [4, 5], [9, 3]],
 '3': [[2, 1], [4, 6]]}

答案 1 :(得分:3)

<强> for
这是一个很好的方法。它可能有import循环,需要from collections import defaultdict d = defaultdict(list) for i, a, b in df.values.tolist(): d[i].append([a, b]) dict(d) {1: [[3, 5], [4, 2], [0, 4]], 2: [[2, 1], [4, 5], [9, 3]], 3: [[2, 1], [4, 6]]} ,并且是多行(所有阻止upvotes的东西)。但它实际上是一个很好的解决方案而且非常快。

numpy.ndarray

<强>替代
通过pd.Series( df[['A', 'B']].values[:, None].tolist(), df.ID.values ).sum(level=0).to_dict() {1: [[3, 5], [4, 2], [0, 4]], 2: [[2, 1], [4, 5], [9, 3]], 3: [[2, 1], [4, 6]]} 获得一点点创意 BTW:请不要实际执行此操作

To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source(including the terminating null character), and should not overlap in memory with source
相关问题