简体   繁体   中英

Converting data-frame into a dictionary by having the multiple lists?

I have a dataframe –mydata- consists of 500 rows something like this:

Id  Name    Score
R1  sam     76
R1  Sosan    8
..  …   … 
R4   jack   2
R4  Tom     76
R4   samy    8
R5  Check    9 
…    …                 

Now, I want to convert the dataframe into a dictionary so that the uniqe Ids become the keys and the rows of the uniques Ids become a list. For example, considering the above example, R1 should be a key and the inside of R1 we should have two lists, or for R4 we should have three lists etc. I have treid the below code, but it ignores the unique Ids :

mydictest= mydata.set_index('Id').T.to_dict('list').copy()

So, my desired output should be like this:

 {'R1': [['sam', 78],['Sosan',8]], 'R4': [['Jack', 2],['Tom', 76],    
 ['samy', 8]]}

Maybe you can try something like this:

df = pd.DataFrame([['R1', 'sam', 78], ['R2', 'rem', 65], ['R1', 'pem', 56]], columns=['Id', 'Name', 'Score'])
d = df.set_index('Id').to_dict(orient='split')

req_dict = {}
for ind, data in zip(d['index'], d['data']):
    if ind in req_dict:
        req_dict[ind].append(data)
    else:
        req_dict[ind] = [data]
print(req_dict)

Output:

{'R1': [['sam', 78], ['pem', 56]], 'R2': [['rem', 65]]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM