1

While converting the pandas dataframe to dictionary, how can I append all the different values to the list ? Reference: Convert a Pandas DataFrame to a dictionary

The answers for this question specifies the solution but it gives me the following output:

df = pd.DataFrame({'a': ['red', 'yellow', 'blue', 'red'], 'b': [0.5, 0.25, 0.125, 0.9]})
>>> df.set_index('a').T.to_dict('list')
{'red': [0.9], 'yellow': [0.25], 'blue': [0.125]}

Expected output:

{'red': [0.5,0.9], 'yellow': [0.25], 'blue': [0.125]}
loadbox
  • 646
  • 14
  • 34
  • 1
    You have a low rate. Important on SO, you have to mark accepted answers by using the tick on the left of the posted answer, below the voting. This will increase your rate. See how this works by visinting this link: http://meta.stackoverflow.com/questions/5234/how-does-accepting-an-answer-work#5235 – Pentium10 Sep 25 '19 at 14:31
  • Thank you. I never did that previously. – loadbox Sep 25 '19 at 14:33

1 Answers1

2

Use DataFrame.groupby with lists and Series.to_dict:

print (df.groupby('a')['b'].apply(list).to_dict())
{'blue': [0.125], 'red': [0.5, 0.9], 'yellow': [0.25]}
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252