【问题标题】:KeyError: None of Float64Index are in the [columns], not sure how to proceedKeyError: Float64Index 都不在 [columns] 中,不确定如何继续
【发布时间】:2020-05-08 00:38:34
【问题描述】:

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

第一个条件很好用。第二个条件(我尝试使用 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 个分数,而不是从 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

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

【问题讨论】:

  • 这可能是因为这两个语句返回不同的东西。 .str.contains() 返回一个带有布尔值的 pandas Series 对象(与原始数据帧具有相同的行数)——这可用于过滤。 .nlargest() 返回一个 pandas Series 对象,其中包含可变数量的行和任何 dtype 的值(在您的示例中为浮点数)——这不能用于过滤。
  • 感谢 Ankur 指出这一点!我能够使用这些信息采取不同的方法,并能够找到我的问题的解决方案。

标签: python pandas dataframe key keyerror


【解决方案1】:

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

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 的过滤版本,按降序对分数进行排序,并使用 .head() 来获取前 n 个值。

【讨论】:

    猜你喜欢
    • 2020-05-10
    • 2020-08-14
    • 2021-11-19
    • 2021-08-04
    • 2020-05-20
    • 2021-01-08
    • 1970-01-01
    • 2023-01-30
    • 2019-09-16
    相关资源
    最近更新 更多