Skip to main content
 首页 » 编程设计

python之在 Dataframe : labels not contained in axis 中删除行

2025年05月04日20thcjp

我有一个包含三列的表:user_id、book_id 和 rating。因此,一行显示用户对一本书的评价。

我正在尝试删除与评分少于 10 本书的用户对应的行。我做了类似于这个问题的答案中描述的事情 Remove low frequency values from pandas.dataframe .这是我的代码:

threshold = 10 
value_counts = ratings['user_id'].value_counts() 
to_remove = value_counts[value_counts <= threshold].index 
ratings.drop(to_remove, axis=0, inplace=True) 

当我运行它时,最后一行出现错误:

ValueError: labels [40518 21743 30824 <...> 47178 46308 30460] not contained in axis 

该表有 979478 行,因此具有这些索引的行应该存在。我做错了什么?

请您参考如下方法:

使用isin,因为user_id不是索引,我们不能在这里使用.drop。

threshold = 10 
value_counts = ratings['user_id'].value_counts() 
to_remove = value_counts[value_counts <= threshold].index 
ratings.loc[~ratings['user_id'].isin(to_remove),:]