1

Lets say I have a dataframe like this:

     first|second|
1      a  |   123|
2      b  |   234|
3      a  |    23|
4      b  |     1|
5      c  |    53|
6      a  |    32|

and I'd like to have a dict like this: dict = {'a': [123, 23, 32], 'b':[234, 1], 'c':[53]}

I have thought to use groupby but couldn't figure out how. I know it should be a for loop somehow: add every element from the first column as keys add every element from the second column to the keys they match.

biohazard90
  • 95
  • 1
  • 7

1 Answers1

2

Group by first column 1 and then do aggregation of column 2 to a list. Then .to_dict():

print( df.groupby('1')['2'].agg(list).to_dict() )

Prints:

{'a': [123, 78, 987], 'b': [56, 21], 'c': [1]}
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91