簡體   English   中英

使用新的鍵名將pandas數據框轉換為字典

[英]Converting pandas dataframe to a dictionary with a new key name

我知道如何將數據幀轉換為字典,但是我不確定如何創建添加了任意鍵名的字典。

假設我有一個類似以下的數據框。

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使用dict comprehension

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM