【问题标题】:Pandas DataFrame KeyError 1Pandas DataFrame KeyError 1
【发布时间】:2020-02-09 13:17:32
【问题描述】:

我尝试使用Pandas 启动以下代码:

if USER_RATINGS:
  my_ratings = pd.DataFrame.from_records(worksheet.get_all_values()).reset_index()
  my_ratings = my_ratings[my_ratings[1] != '']
  my_ratings = pd.DataFrame({
      'user_id': "943",
      'title':list(map(str, my_ratings[0])),
      'listen_count': list(map(float, my_ratings[1]))
  })
my_ratings.merge(song_df_2, on="title", how="left")
song_df = song_df[song_df.user_id != "943"]
song_df = song_df.append(my_ratings, ignore_index=True)
if users.shape[0] == 943:
  users = users.append(users.iloc[942], ignore_index=True)
  users["user_id"][943] = "943"
print("Added your %d ratings; you have great taste!" % len(my_ratings))
song_df[song_df.user_id=="943"].merge(music[['song_id', 'title']])

但是我有以下错误:

During handling of the above exception, another exception occurred:
KeyError
Traceback (most recent call last)
2 frames
/usr/local/lib/python3.6/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2897                 return self._engine.get_loc(key)
   2898             except KeyError:
-> 2899                 return self._engine.get_loc(self._maybe_cast_indexer(key))
[...]
KeyError: 1

您能帮我弄清楚如何解决这个问题吗?

【问题讨论】:

  • my_ratings[my_ratings[1] != '']您没有名为1的列

标签: python pandas dataframe recommender-systems


【解决方案1】:

my_ratings = my_ratings[my_ratings[1] != '']

看起来 1 (Key) 不是列名 (KeyError)。如果此语句的目的是删除空行,请尝试以下操作:

my_ratings.dropna(inplace=True)

希望这会有所帮助!

【讨论】:

  • TypeError Traceback(最近一次调用最后一次) in () 4 my_ratings = pd.DataFrame({ 5 'user_id': "943", -- --> 6 'title':list(map(str, my_ratings[0])), 7 'listen_count': list(map(float, my_ratings[1])) 8 }) TypeError: 'NoneType' object is not subscriptable
  • 它成功了,然后我在映射时遇到了错误。
猜你喜欢
  • 1970-01-01
  • 2015-07-27
  • 1970-01-01
  • 2017-01-07
  • 1970-01-01
  • 1970-01-01
  • 2019-06-09
  • 2021-05-26
  • 1970-01-01
相关资源
最近更新 更多