Reputation: 83
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
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