【问题标题】:Pandas Groupby a List of dictionaries to one dictionaryPandas Groupby 一个字典列表到一个字典
【发布时间】:2017-04-11 20:13:53
【问题描述】:

我正在解决一个字典列表具有相同键的问题,我想将所有值聚合到每个键的列表中。

    x = [
    {'firstName': 'Tom', 'lastName': 'Fyre', 'email': 'tom_f@gmail'},
    {'firstName': 'Jerry', 'lastName': 'Brat', 'email': 'jerry_b@gmail'},
    {'firstName': 'Phil', 'lastName': 'Hughes', 'email': 'phil_h@gmail'}
]

我想将上面的字典列表转换为一个字典,如下所示:

    results = {
        'firstName': ['Tom', 'Jerry', 'Phil'],
        'lastName': ['Fyre', 'Brat', 'Hughes'],
        'email': ['tom_f@gmail', 'jerry_b@gmail', 'phil_h@gmail']
    }

【问题讨论】:

    标签: python pandas dictionary


    【解决方案1】:

    我认为你需要to_dict 和参数orient='list'

    df1 = pd.DataFrame(x)
    print (df1)
               email firstName lastName
    0    tom_f@gmail       Tom     Fyre
    1  jerry_b@gmail     Jerry     Brat
    2   phil_h@gmail      Phil   Hughes
    
    results = df1.to_dict(orient='list')
    print (results)
    {'firstName': ['Tom', 'Jerry', 'Phil'], 
    'email': ['tom_f@gmail', 'jerry_b@gmail', 'phil_h@gmail'], 
    'lastName': ['Fyre', 'Brat', 'Hughes']}
    

    【讨论】:

      猜你喜欢
      • 2021-01-11
      • 2017-12-22
      • 2021-09-22
      • 2016-02-14
      • 2017-06-19
      • 1970-01-01
      • 2022-01-22
      • 2020-12-30
      • 2018-09-18
      相关资源
      最近更新 更多