首页 > 解决方案 > 如何遍历数据框

问题描述

我有一个用户、书籍和评分的数据集,我想找到对特定书籍评分高的用户,对于那些我想找到他们也喜欢的其他书籍的用户。

我的数据看起来像:

df.sample(5)

    User-ID     ISBN    Book-Rating
49064   102967  0449244741  8
60600   251150  0452264464  9
376698  52853   0373710720  7
454056  224764  0590416413  7
54148   25409   0312421273  9

到目前为止我做了:

df_p = df.pivot_table(index='ISBN', columns='User-ID', values='Book-Rating').fillna(0)
lotr = df_p.ix['0345339703'] # Lord of the Rings Part 1
like_lotr = lotr[lotr > 7].to_frame()
users = like_lotr['User-ID']

最后一行失败

KeyError:“用户 ID”

我想获得对 LOTR > 7 评分的用户,让这些用户进一步从矩阵中找到他们也喜欢的电影。

帮助将不胜感激。谢谢。

标签: pythonpandasnumpy

解决方案


在您的like_lotr数据框中'User-ID'是索引的名称,您不能像普通列一样选择它。这就是为什么这条线users = like_lotr['User-ID']会引发KeyError. 它不是一列。

此外ix已弃用,最好loc在您的情况下使用。并且不要加引号:它必须是整数,因为'User-ID'最初是一列整数(至少来自您的示例)。

试试这样:

df_p = df.pivot_table(index='ISBN', columns='User-ID', values='Book-Rating').fillna(0)
lotr = df_p.loc[452264464] # used another number from your sample dataframe to test this code.
like_lotr = lotr[lotr > 7].to_frame()
users = like_lotr.index.tolist()

user现在是一个包含您想要的 id 的列表。

使用上面的小样本和我用来测试的数字,user[251150]


另一种解决方案是使用reset_index. 最后两个 lins 应该如下所示:

like_lotr = lotr[lotr > 7].to_frame().reset_index()
users = like_lotr['User-ID']

reset_index将索引放回列中。


推荐阅读