Pandas: Convert Data to List Format

I have a dataframe like this:

col1, col2
A      0
A      1
B      2
C      3

I would like to get the following:

{ A: [0,1], B: [2], C: [3] }

I tried:

df.set_index('col1')['col2'].to_dict()

but this is not entirely correct. The first problem that I have is "A", it repeats, I get only A: 1 (0 is overwritten). How to fix?

+4
source share
2 answers

You can use the understanding of the dictionary in the group.

>>> {idx: group['col2'].tolist() 
     for idx, group in df.groupby('col1')}
{'A': [0, 1], 'B': [2], 'C': [3]}
+5
source

Decision

df.groupby('col1')['col2'].apply(lambda x: x.tolist()).to_dict()

{'A': [0, 1], 'B': [2], 'C': [3]}
+3
source

All Articles