Renton
Renton

Reputation: 83

How to merge rows of pandas DataFrame into list and transform this DataFrame into dict

I have a DataFrame

  col1  col2
 0  a   1
 1  b   2
 2  c   3
 3  a   4
 4  b   5

I want it to be transformed as follows:

   col1  col2
0   a   [1, 4]
1   b   [2, 5]
2   c   [3]

So that the similar elements of col1 were unique and corresponding values from col2 were merged into the list.

That was the first part. The second is: how to export this DataFrame into python dict?

So, as a result, I want to have the following dict

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

Upvotes: 3

Views: 41

Answers (1)

akuiper
akuiper

Reputation: 214927

Merge the values:

df.groupby('col1').col2.apply(list)
#col1
#a    [1, 4]
#b    [2, 5]
#c       [3]
#Name: col2, dtype: object

Convert to dictionary:

df.groupby('col1').col2.apply(list).to_dict()
# {'a': [1, 4], 'b': [2, 5], 'c': [3]}

Upvotes: 4

Related Questions