pandas dataframe to_dict两列作为索引,第三列作为值

时间:2018-05-01 16:36:03

标签: python pandas

我有一个pandas数据框如下:

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

我想生成一个字典,其中有2列'User'和'ASIN'作为键,第三列'Rating'作为值。如下所示:

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

我该怎么做?

4 个答案:

答案 0 :(得分:5)

使用嵌套字典理解:

{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()}

请注意,这会映射到列表,因为结果值没有理由应该是唯一的。

答案 1 :(得分:2)

你的问题不是很清楚,但这样做你想要的吗?

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

因此,如果将其分配给my_dict,那么您有

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

答案 2 :(得分:0)

只要您拥有唯一的用户ID,这就应该有效。

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

或者,您可以过滤DataFrame以获得评级

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

答案 3 :(得分:0)

您可以使用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