Darin McCoy
Darin McCoy

Reputation: 71

Pandas dictionary transformation to dictionary

I have this dataframe

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

and I would like to turn it into this

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

What is an elegant way to do that with pandas?

Upvotes: 0

Views: 36

Answers (2)

Ynjxsjmh
Ynjxsjmh

Reputation: 30032

You can use

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

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

Upvotes: 1

Mark Wang
Mark Wang

Reputation: 2757

Try:

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

Upvotes: 1

Related Questions