KeyError: None of Float64Index are in the [columns], not sure how to proceed

KeyError: None of Float64Index are in the [columns], not sure how to proceed

我正在尝试 return 我的 Dataframe 中满足两个条件的所有行。

第一个条件很好。第二种情况(我尝试使用 nlargest(10) 到 return 基于前 10 个分数的行)给我以下错误:

 File "/Users/[extracted]/Desktop/imdbnew.py", line 21, in <module>
    comedy_high = IMDB[IMDB['Score'].nlargest(10)]
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pandas/core/frame.py", line 2806, in __getitem__
    indexer = self.loc._get_listlike_indexer(key, axis=1, raise_missing=True)[1]
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pandas/core/indexing.py", line 1552, in _get_listlike_indexer
    self._validate_read_indexer(
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pandas/core/indexing.py", line 1640, in _validate_read_indexer
    raise KeyError(f"None of [{key}] are in the [{axis_name}]")
KeyError: "None of [Float64Index([9.6, 9.4, 9.4, 9.4, 9.4, 9.3, 9.2, 9.1, 9.1, 9.0], dtype='float64')] are in the [columns]"

产生该错误的代码如下:

import pandas
from pandas import DataFrame
import numpy

# Import IMDB data
data = pandas.read_csv('movies.csv')
col = data[['Title', 'Year', 'Score', 'Genre', 'Director',
                'Runtime', 'Revenue']]

IMDB = pandas.DataFrame(data, columns = ['Title', 'Year', 'Score', 'Genre',
                                         'Director', 'Runtime', 'Revenue'])


comedy_high = IMDB[IMDB['Score'].nlargest(10)]
#comedy_df = IMDB[(IMDB['Genre'].str.contains("Comedy"))]

print(comedy_high)

但是,如果我尝试只打印出前 10 个分数,而不是 return Dataframe 中与之对应的行,我会得到一个结果:

comedy_high = IMDB['Score'].nlargest(10)

结果是:

9603    9.6
1645    9.4
3914    9.4
5482    9.4
5979    9.4
0       9.3
9       9.2
5428    9.1
6891    9.1
1       9.0
Name: Score, dtype: float64

这真的让我很沮丧,有人可以帮忙吗?我是一名新手程序员;我一直在阅读其他类似的问题,并测试提供的答案,但无法找到解决方案。非常感谢您的帮助!

我能够通过以下代码弄清楚如何解决我正在寻找的问题:

comedy_df = IMDB[(IMDB['Genre'].str.contains("Comedy"))]
comedy = pandas.DataFrame(comedy_df)
comedy_high = comedy.sort_values('Score', ascending=False).head(10)
print(comedy_high)

正如 Ankur 在他的评论中提到的,我无法使用 .nlargest() 来过滤 Dataframe。相反,我根据我正在研究的类型创建了原始 Dataframe 的过滤版本,按降序对分数进行排序,并使用 .head() 获取前 n 个值。