简体   繁体   中英

pandas dataframe to_dict two columns as indexes and third as value

I have a pandas dataframe as below:

User              ASIN             Rating
A23VKINWRY6J92    1476783284       5
A3HC4SRK7B2AXR    1496177029       5
AE12HJWB5ODOD     B00K2GAUC0       4
AL4RYO265J1G      061579615X       3

I want to generate a dictionary which has 2 columns 'User' and 'ASIN' as keys and third column 'Rating' as the value. Something like below:

my_dict[A23VKINWRY6J92][1476783284] = 5
my_dict[A3HC4SRK7B2AXR][1496177029] = 5
my_dict[AE12HJWB5ODOD][B00K2GAUC0] = 4
my_dict[AL4RYO265J1G][061579615X] = 3

How can I do this?

Using nested dict comprehension:

{u: {a: list(df.Rating[(df.User == u) & (df.ASIN == a)].unique()) for a in df.ASIN[df.User == u].unique()} for u in df.User.unique()}

Note that this maps to lists, as there is no reason the resulting value should be unique.

Your question isn't too clear but does this do what you want?

>>> D = df.groupby(['User','ASIN'])['Rating'].apply(list).to_dict()
>>> {key[0]:{key[1]:val} for key, val in D.items()}
{('A23VKINWRY6J92', '1476783284'): [5], ('A3HC4SRK7B2AXR', '1496177029'): [5], ('AE12HJWB5ODOD', 'B00K2GAUC0'): [4], ('AL4RYO265J1G', '061579615X'): [3]}

So if this is assigned to my_dict then you have

>>> my_dict['A23VKINWRY6J92']['1476783284']
[5]

etc

This should work as long as you have unique User ID's.

my_dict ={d['ASIN'] : {d['User'] : d['Rating']} for d in df.to_dict(orient='records')}

Alternatively you can filter the DataFrame to obtain the rating

rating = df.loc[(df['User']=='A23VKINWRY6J92') & (df['ASIN']=='1476783284'), 'Rating'][0]

You can using defaultdict

from collections import defaultdict
d = defaultdict(dict)
for _,x in df.iterrows():
    d[x['User']][x['ASIN']] = x['Rating'] 
d=dict(d)
d['A23VKINWRY6J92']['1476783284']
Out[108]: 5

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