You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

执行recommend1函数时出现'numpy.float64'不可迭代错误求助

报错分析与代码修改建议

执行recommend1('Avatar')函数时,代码行movies_list = sorted([enumerate(distances[0])], reverse=True, key = lambda x:x[1])[1:6]触发TypeError,报错信息:'numpy.float64' object is not iterable。

用户原代码

def recommend1(movie):
  movie_index = new_df[new_df['title']== movie].index[0]
  distances = similarity[movie_index]
  movies_list = sorted([enumerate(distances[0])], reverse=True , key = lambda x:x[1])[1:6]

for i in movies_list :
 print(new_df.iloc[i[0]].title)

完整报错栈

TypeError                                 Traceback (most recent call last)
<ipython-input-63-76a841473d9d> in <module>
----> 1 recommend1('Avatar')

<ipython-input-61-27f7c47f4ecd> in recommend1(movie)
    2   movie_index = new_df[new_df['title']== movie].index[0]
    3   distances = similarity[movie_index]
----> 4   movies_list = sorted([enumerate(distances[0])], reverse=True , key = lambda x:x[1])[1:6]
    5 
    6   for i in movies_list :

TypeError: 'numpy.float64' object is not iterable

问题原因

  1. similarity[movie_index]返回的是一维数组,存储当前电影与所有其他电影的相似度值。distances[0]取的是数组第一个元素(单个numpy.float64数值),而enumerate()需要接收可迭代对象,传入单个数值直接触发迭代错误。
  2. 原代码将enumerate(distances[0])套在列表里,排序后只会得到包含单个枚举对象的列表,切片[1:6]会返回空列表,无法拿到推荐结果。
  3. for循环缩进错误,位于函数外部会导致变量作用域问题。

修改后的代码

def recommend1(movie):
    movie_index = new_df[new_df['title'] == movie].index[0]
    distances = similarity[movie_index]
    # 直接枚举整个distances数组,去除多余的列表包裹和错误索引
    movies_list = sorted(enumerate(distances), reverse=True, key=lambda x: x[1])[1:6]
    
    # 将循环缩进至函数内部,确保变量可访问
    for i in movies_list:
        print(new_df.iloc[i[0]].title)

内容的提问来源于stack exchange,提问作者Prince Thakkar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 20:33:01