python pandas convert dataframe to dictionary with multiple values

前端 未结 2 2020
闹比i
闹比i 2021-02-05 21:21

I have a dataframe with 2 columns Address and ID. I want to merge IDs with the same addresses in a dictionary

import pandas as pd, numpy as np

df = pd.DataFrame         


        
相关标签:
2条回答
  • 2021-02-05 21:56

    I think you can use groupby and a dictionary comprehension here:

    >>> df
      Address  ID
    0    12 A  Aa
    1    66 C  Bb
    2    10 B  Cc
    3    10 B  Dd
    4    12 A  Ee
    5    12 A  Ff
    >>> {k: list(v) for k,v in df.groupby("Address")["ID"]}
    {'66 C': ['Bb'], '12 A': ['Aa', 'Ee', 'Ff'], '10 B': ['Cc', 'Dd']}
    
    0 讨论(0)
  • 2021-02-05 22:12

    In response to the comment about multiple columns:

    >>> df
      Address  ID  Name
    0    12 A  Aa  Alpha
    1    66 C  Bb  Bravo
    2    10 B  Cc  Charlie
    3    10 B  Dd  Delta
    4    12 A  Ee  Edgar
    5    12 A  Ff  Frank
    >>> {k: v.to_dict() for k,v in df.groupby("Address")}
    
    0 讨论(0)
提交回复
热议问题