【问题标题】:Pandas : Getting indexes of a series providing multiple filtersPandas:获取提供多个过滤器的系列的索引
【发布时间】:2017-06-25 14:32:05
【问题描述】:

我正在迭代一个数据框。在每次迭代中,我需要获取值等于 5 或​​ 4 的系列的索引。下面的代码给了我值为 5 的索引(另一个问题:实际上我得到了索引和值。另一个问题是得到只有索引。我试过print row[row ==5].index[0],但它不适合我)

def get_top_rated_movies(user_ratings):
for index, row in user_ratings.iterrows():
    print row[row == 5]

我想我必须做row[row == 5 || row == 4] 之类的事情,但我不知道。

这里的“user_ratings”是一个数据框。每行是一个用户,列是一部电影,我在其中存储用户对电影的评分。我需要为每个用户获取 4 或 5 个评分的电影。所以,我遍历数据框,上面的代码给了我(电影 ID 和评分)

movie_id
1      5
9      5
13     5
15     5
16     5
19     5
32     5
42     5
45     5
48     5
50     5
55     5
57     5
59     5
87     5

【问题讨论】:

  • 你能添加一些数据和想要的输出吗?
  • 那么第二个或最后一个解决方案有效吗?
  • 谢谢。用户评分[(用户评分== 5)| (user_ratings == 4)] 对我有用,其中 user_ratings 是一个系列。但我得到的结果是指数和评级。在我的问题中查看我的输出。如何获取唯一索引?
  • 使用user_ratings.index[(user_ratings == 5) | (user_ratings == 4)]
  • 是的,它正在工作

标签: python pandas


【解决方案1】:

我觉得你可以用boolean indexing:

如果user_ratingsSeries

user_ratings[(user_ratings == 5) | (user_ratings == 4)]

或者更好:

user_ratings[user_ratings.isin([4,5])]

如果需要索引过滤器:

user_ratings.index[(user_ratings == 5) | (user_ratings == 4)]
user_ratings.index[user_ratings.isin([4,5])]

或者先过滤Series再获取索引:

user_ratings[(user_ratings == 5) | (user_ratings == 4)].index
user_ratings[user_ratings.isin([4,5])].index

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-21
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2019-02-09
    • 2023-03-03
    • 1970-01-01
    相关资源
    最近更新 更多