Numpy matrix to Pandas DataFrame



我有一个numpy用户 - 项目矩阵,每行都对应用户,每个列对应于项目。我想在熊猫数据框中转换矩阵,如下所示:

   user  item  rating
0     1  1907     4.0
1     1  1028     5.0
2     1   608     4.0
3     1  2692     4.0
4     1  1193     5.0

我使用以下代码生成数据框:

predictions = pd.DataFrame(data=pred)
predictions = predictions.stack().reset_index(name='rating')
predictions.columns = ['user', 'item', 'rating']

我得到这样的DF:

        user  item    rating
0          0     0  5.000000
1          0     1  0.000000
2          0     2  0.000000
3          0     3  0.000000

pandas有没有办法将用户中的每个值和项目列映射到列表中存储的值?用户列表中的第一个值,用户列表中的值5的用户应在用户列表中的第6个元素等中映射。我正在尝试使用:

predictions[["user"]].apply(lambda value: users[value])

但是我有一个我不明白的索引,因为我的用户列表的尺寸为96

IndexError: ('index 96 is out of bounds for axis 1 with size 96', 'occurred at index user')

我的错是在此代码中:

while not session.should_stop():
    predictions = session.run(decoder_op)
    pred = np.vstack((pred, predictions))

刚替换为:

np.vstack((pred, predictions))

它就像以下魅力一样工作:

predictions['user'] = predictions['user'].map(lambda value: users[value])
predictions['item'] = predictions['item'].map(lambda value: items[value])

最新更新