Home > Mobile >  Pandas dictionary transformation to dictionary
Pandas dictionary transformation to dictionary

Time:06-01

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?

CodePudding user response:

Try:

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

CodePudding user response:

You can use

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

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