python - 如何遍历数据框
问题描述
我有一个用户、书籍和评分的数据集,我想找到对特定书籍评分高的用户,对于那些我想找到他们也喜欢的其他书籍的用户。
我的数据看起来像:
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 评分的用户,让这些用户进一步从矩阵中找到他们也喜欢的电影。
帮助将不胜感激。谢谢。
解决方案
在您的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
将索引放回列中。
推荐阅读
- c - 尝试更改字符串中的值时,C 中的 EXC_BAD_ACCESS (code=2)
- php - Laravel,如果未登录,如何重定向到不同的登录页面
- matlab - 如何从 MATLAB 脚本初始化 Simulink 模型的常量?
- javascript - 防止默认值在我的代码中不起作用
- python - 查找要从字典中删除的用户数据的方法?
- react-native - 带有抽屉导航器的底部选项卡导航器 React Native
- graphql - GQL 方案接受相同键的多个数据结构
- python - NameError:类名未定义,尽管已导入
- spring-boot - 连接被拒绝:运行 Docker Compose 时
- sql - 报表生成器不从 sql-query 进行计算