Guru A
Guru A

Reputation: 23

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?

Upvotes: 2

Views: 1094

Answers (4)

BENY
BENY

Reputation: 323326

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

Upvotes: 0

Yashodhan Joglekar
Yashodhan Joglekar

Reputation: 33

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]

Upvotes: 0

Dan
Dan

Reputation: 45752

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

Upvotes: 2

Ami Tavory
Ami Tavory

Reputation: 76346

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.

Upvotes: 5

Related Questions