gpt4 book ai didi

python - 将 pandas 数据框转换为具有新键名的字典

转载 作者:行者123 更新时间:2023-12-01 02:49:58 25 4
gpt4 key购买 nike

我知道如何将数据帧转换为字典,但我不确定如何创建添加任意键名称的字典。

假设我有一个如下所示的数据框。

raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'],
'company': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd', '2nd'],
'name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze', 'Jacon', 'Ryaner', 'Sone', 'Sloan', 'Piger', 'Riani', 'Ali'],
'preTestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3],
'postTestScore': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]}

df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'name', 'preTestScore', 'postTestScore'])

df.head()
Out[96]:
regiment company name preTestScore postTestScore
0 Nighthawks 1st Miller 4 25
1 Nighthawks 1st Jacobson 24 94
2 Nighthawks 2nd Ali 31 57
3 Nighthawks 2nd Milner 2 62
4 Dragoons 1st Cooze 3 70

我想按“名称”分组并计算“preTestScore”中的最大值,最后创建一个字典,如下所示。

{'Miller': {'maxTestScore': 4},
'Jacobson': {'maxTestScore': 24}, ...}

在这里,我添加了一个新的键名称“maxTestScore”。我怎样才能用任意键名来实现这一点?提前非常感谢您。

最佳答案

您可以将字典理解groupby结合使用:

d = {k:{'maxTestScore':v.max()} for k,v in df.groupby('name')['preTestScore']}
print (d)

{'Piger': {'maxTestScore': 3},
'Milner': {'maxTestScore': 2},
'Sone': {'maxTestScore': 31},
'Jacon': {'maxTestScore': 4},
'Cooze': {'maxTestScore': 3},
'Sloan': {'maxTestScore': 2},
'Riani': {'maxTestScore': 2},
'Miller': {'maxTestScore': 4},
'Ali': {'maxTestScore': 31},
'Ryaner': {'maxTestScore': 24},
'Jacobson':{'maxTestScore': 24}}

另一个解决方案:

d = {k:{'maxTestScore':v} for k,v in df.groupby('name')['preTestScore'].max().iteritems()}
print (d)

{'Piger': {'maxTestScore': 3},
'Milner': {'maxTestScore': 2},
'Sone': {'maxTestScore': 31},
'Jacon': {'maxTestScore': 4},
'Cooze': {'maxTestScore': 3},
'Sloan': {'maxTestScore': 2},
'Riani': {'maxTestScore': 2},
'Miller': {'maxTestScore': 4},
'Ali': {'maxTestScore': 31},
'Ryaner': {'maxTestScore': 24},
'Jacobson':{'maxTestScore': 24}}

关于python - 将 pandas 数据框转换为具有新键名的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44901844/

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