Converting a dataframe to dictionary with multiple values

后端 未结 2 1444
太阳男子
太阳男子 2021-02-10 02:09

I have a dataframe like

Sr.No   ID       A         B          C         D
 1     Tom     Earth    English      BMW
 2     Tom     Mars     Spanish      BMW               


        
2条回答
  •  半阙折子戏
    2021-02-10 02:36

    Grouping by 'ID' and apply to_dict to each group with orient='list' comes pretty close:

    df.groupby('ID').apply(lambda dfg: dfg.to_dict(orient='list')).to_dict()
    Out[25]: 
    {'John': {'A': ['Venus', nan],
      'B': ['Portugese', 'German'],
      'C': ['Mercedes', 'Audi'],
      'D': ['Blue', 'Red'],
      'ID': ['John', 'John'],
      'Sr.No': [4, 5]},
     'Michael': {'A': ['Mercury'],
      'B': ['Hindi'],
      'C': ['Audi'],
      'D': ['Yellow'],
      'ID': ['Michael'],
      'Sr.No': [3]},
     'Tom': {'A': ['Earth', 'Mars'],
      'B': ['English', 'Spanish'],
      'C': ['BMW', 'BMW'],
      'D': [nan, 'Green'],
      'ID': ['Tom', 'Tom'],
      'Sr.No': [1, 2]}}
    

    It should just be a matter of formatting the result slightly.

    Edit: to remove 'ID' from the dictionaries:

    df.groupby('ID').apply(lambda dfg: dfg.drop('ID', axis=1).to_dict(orient='list')).to_dict()
    Out[5]: 
    {'John': {'A': ['Venus', nan],
      'B': ['Portugese', 'German'],
      'C': ['Mercedes', 'Audi'],
      'D': ['Blue', 'Red'],
      'Sr.No': [4, 5]},
     'Michael': {'A': ['Mercury'],
      'B': ['Hindi'],
      'C': ['Audi'],
      'D': ['Yellow'],
      'Sr.No': [3]},
     'Tom': {'A': ['Earth', 'Mars'],
      'B': ['English', 'Spanish'],
      'C': ['BMW', 'BMW'],
      'D': [nan, 'Green'],
      'Sr.No': [1, 2]}}
    

提交回复
热议问题