Pandas: Convert dataframe to dict of lists

后端 未结 2 752
被撕碎了的回忆
被撕碎了的回忆 2021-01-05 08:18

I have a dataframe like this:

col1, col2
A      0
A      1
B      2
C      3

I would like to get this:

{ A: [0,1], B: [2],          


        
相关标签:
2条回答
  • 2021-01-05 08:50

    You can use a dictionary comprehension on a groupby.

    >>> {idx: group['col2'].tolist() 
         for idx, group in df.groupby('col1')}
    {'A': [0, 1], 'B': [2], 'C': [3]}
    
    0 讨论(0)
  • 2021-01-05 09:11

    Solution

    df.groupby('col1')['col2'].apply(lambda x: x.tolist()).to_dict()
    
    {'A': [0, 1], 'B': [2], 'C': [3]}
    
    0 讨论(0)
提交回复
热议问题