如何在 python 中将具有多个列表值的一键数据框制作成字典?

How to make a dataframe with one key to multiple list values to a dictionary in python?

我有一个这样的数据框

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

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

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

但它给了我一个 return 每个 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])}

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

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]]}

defaultdict
这是一个很好的方法。它可能有一个 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]]}

备选
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]]}