gpt4 book ai didi

python - Pandas Groupby 字典列表到一个字典

转载 作者:太空宇宙 更新时间:2023-11-04 10:01:29 25 4
gpt4 key购买 nike

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

    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']
}

最佳答案

我想你需要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']}

关于python - Pandas Groupby 字典列表到一个字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43345533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com