【发布时间】: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