簡體   English   中英

使用唯一列值作為鍵轉換Pandas Dataframe to_dict()

[英]Convert Pandas Dataframe to_dict() with unique column values as keys

如何使用唯一列值作為字典的鍵將pandas數據幀轉換為dict? 在這種情況下,我想使用唯一的用戶名作為密鑰。

到目前為止,根據此處和在線信息,我的進展如下。

我的測試數據幀:

import pandas
import pprint

df = pandas.DataFrame({
    'username': ['Kevin', 'John', 'Kevin', 'John', 'Leslie', 'John'], 
    'sport': ['Soccer', 'Football', 'Racing', 'Tennis', 'Baseball', 'Bowling'],
    'age': ['51','32','20','19','34','27'],
    'team': ['Cowboyws', 'Packers', 'Sonics', 'Raiders', 'Wolves', 'Lakers']
})

我可以通過這樣做來創建一個字典:

dct = df.to_dict(orient='records')
pprint.pprint(dct, indent=4)

>>>>[{'age': '51', 'sport': 'Soccer', 'team': 'Cowboyws', 'username': 'Kevin'},
    {'age': '32', 'sport': 'Football', 'team': 'Packers', 'username': 'John'},
    {'age': '20', 'sport': 'Racing', 'team': 'Sonics', 'username': 'Kevin'},
    {'age': '19', 'sport': 'Tennis', 'team': 'Raiders', 'username': 'John'},
    {'age': '34', 'sport': 'Baseball', 'team': 'Wolves', 'username': 'Leslie'},
    {'age': '27', 'sport': 'Bowling', 'team': 'Lakers', 'username': 'John'}]

我嘗試使用groupbyapply方法使我更接近,但它將所有值轉換為列表。 我希望它們保留為字典,以便我可以保留每個值的鍵:

result = df.groupby('username').apply(lambda x: x.values.tolist()).to_dict()
pprint.pprint(result, indent=4)

{   'John': [   ['32', 'Football', 'Packers', 'John'],
                ['19', 'Tennis', 'Raiders', 'John'],
                ['27', 'Bowling', 'Lakers', 'John']],
    'Kevin': [   ['51', 'Soccer', 'Cowboyws', 'Kevin'],
                 ['20', 'Racing', 'Sonics', 'Kevin']],
    'Leslie': [['34', 'Baseball', 'Wolves', 'Leslie']]}

這是我想要的結果:

{   
    'John': [{'age': '32', 'sport': 'Football', 'team': 'Packers', 'username': 'John'},
             {'age': '19', 'sport': 'Tennis', 'team': 'Raiders', 'username': 'John'},
             {'age': '27', 'sport': 'Bowling', 'team': 'Lakers', 'username': 'John'}],
    'Kevin': [{'age': '51', 'sport': 'Soccer', 'team': 'Cowboyws', 'username': 'Kevin'},
              {'age': '20', 'sport': 'Racing', 'team': 'Sonics', 'username': 'Kevin'}],
    'Leslie': [{'age': '34', 'sport': 'Baseball', 'team': 'Wolves', 'username': 'Leslie'}]
}

使用groupbyapply 在apply中,使用“記錄”方向調用to_dict (類似於你已經想到的)。

df.groupby('username').apply(lambda x: x.to_dict(orient='r')).to_dict()

我更喜歡在這里使用for循環,你也可以drop username名列,因為它是多余的

d = {x: y.drop('username',1).to_dict('r') for x , y in df.groupby('username')}
d
Out[212]: 
{'John': [{'age': '32', 'sport': 'Football', 'team': 'Packers'},
  {'age': '19', 'sport': 'Tennis', 'team': 'Raiders'},
  {'age': '27', 'sport': 'Bowling', 'team': 'Lakers'}],
 'Kevin': [{'age': '51', 'sport': 'Soccer', 'team': 'Cowboyws'},
  {'age': '20', 'sport': 'Racing', 'team': 'Sonics'}],
 'Leslie': [{'age': '34', 'sport': 'Baseball', 'team': 'Wolves'}]}

暫無
暫無

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

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