我在Python中遇到了一个问题,要从Pandas数据框中高效地创建字典。这是我的DF。

             User-ID  Book-Rating
ISBN
0553297627   230402     1
0553297627   124942     7
0553297627   238120     0
0553297627   227705     2
0553297627   234623     10
0553297627   172742     5

我想要这样的结构:
{
'0553297627': {
                '230402': 1,
                '124942': 7,
                '238120': 0,
                '227705': 2,
                '234623': 10
                '172742': 5,
             }
... more books here
}

我是用一个循环来做的,这很费时。我的代码是:
...
isbn = '0553297627'
df_values = df.values
d = {key: value for (key, value) in df_values}  <--- I want to avoid!
dict[isbn] = d

最佳答案

您可以将groupbyzip一起使用,最后转换to_dict

print (df.groupby(level='ISBN')
         .apply(lambda x: dict(zip(x['User-ID'], x['Book-Rating'])))
         .to_dict())
{
    553297627:
    {230402: 1, 172742: 5, 238120: 0, 227705: 2, 124942: 7, 234623: 10}
}

关于python - 从没有循环的Pandas数据框中创建带有字典的字典,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41889942/

10-14 19:35
查看更多