我有三列数据报,打算以给定的格式在字典中转换:
数据报:
user_id item_id ratings
3 2 3
3 3 4
1 3 1
2 1 4
用户数 = 3
项目编号 = 3
评级 = 0 到 5
字典=
{user_id1:[rating_for_item1, rating_for_item2, rating_for_item3],
user_id2:[.same as previous.],
user_id3:[..same as prev..]}
例如,
{1:[0,0,1], 2:[4,0,0], 3:[0,3,4]}
所以,我能做的就是输出如下:
{1:{3:1}, 2:{1:4}, 3:{2:3, 3:4}} #{user_id:{item_id:rating}.....}
上面输出的代码如下:
import pandas as pd
data = {}
cols = ['user_id', 'item_id', 'ratings']
pf = pd.read_csv('filename', sep='\t', names= cols)
for user, item, rate in pf.values: data.setdefault(user,{})[item] = rate
print data
我的代码中缺少什么,或者我完全走错了路。请帮忙。