Pandas字典转换为字典

Pandas dictionary transformation to dictionary

我有这个数据框

mylist = [['a', 1], ['a', 2], ['b', 3], ['b', 4]]
df = pd.DataFrame(mylist)

我想把它变成这个

desired_dict = {'a':[1, 2], 'b':[3, 4]}

使用 pandas 的优雅方法是什么?

尝试:

df.groupby(0)[1].agg(list).to_dict()

你可以使用

out = df.groupby(0)[1].apply(list).to_dict()
print(out)

{'a': [1, 2], 'b': [3, 4]}