KeyError:Float64Index都不在[列]中,不确定如何进行处理

问题描述 投票:0回答:1

我正在尝试从我的数据框返回满足两个条件的所有行。

第一个条件很好。第二个条件(我尝试使用nlargest(10)返回基于前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个得分,而不是从数据框中返回与之相对应的行,则会得到结果:

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

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

python pandas dataframe key keyerror
1个回答
0
投票

我能够通过以下代码弄清楚如何解决我要找的东西:

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()来过滤数据框。相反,我根据要查看的流派创建了原始数据框的过滤版本,将成绩按降序排序,然后使用.head()获取前n个值。

© www.soinside.com 2019 - 2024. All rights reserved.