keyerror panda+jupiter 笔记本,带有 csv 文件

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

我在kaggle上找到了一个csv文件,所以我下载了它来学习它,我导入了panda模块,然后使用它读取了该文件,然后我只保留了工资和工资货币列,然后尝试使用该货币获得最高和最低工资是美元,所以我尝试使用 loc,但出现了一个如下所示的错误:

KeyError                                  Traceback (most recent call last)
Cell In[29], line 2
      1 df.head(10)
----> 2 df=df.loc[df['salary_currency']=="USD"]
      3 max_salary=df['salary'].max()
      4 min_salary=df['salary'].min()

File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pandas\core\series.py:1112, in Series.__getitem__(self, key)
   1109     return self._values[key]
   1111 elif key_is_scalar:
-> 1112     return self._get_value(key)
   1114 # Convert generator to list before going through hashable part
   1115 # (We will iterate through the generator there to check for slices)
   1116 if is_iterator(key):

File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pandas\core\series.py:1228, in Series._get_value(self, label, takeable)
   1225     return self._values[label]
   1227 # Similar to Index.get_value, but we do not fall back to positional
-> 1228 loc = self.index.get_loc(label)
   1230 if is_integer(loc):
   1231     return self._values[loc]

File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pandas\core\indexes\range.py:417, in RangeIndex.get_loc(self, key)
    415         raise KeyError(key) from err
...
--> 417     raise KeyError(key)
    418 self._check_indexing_error(key)
    419 raise KeyError(key)

KeyError: 'salary_currency'

这是我的代码:

    import pandas as pd
    Data = pd.read_csv('ds_salaries.csv')
    df=Data[['salary_currency','salary']]
    df=df.loc[df['salary_currency']=="USD"]
    max_salary=df['salary'].max()
    min_salary=df['salary'].min()
    print(max_salary,"\n",min_salary,"\n",df)

这是使用 LOC 之前的最后一个数据帧:

salary_currency salary
0   EUR 80000
1   USD 30000
2   USD 25500
3   USD 175000
4   USD 120000
... ... ...
3750    USD 412000
3751    USD 151000
3752    USD 105000
3753    USD 100000
3754    INR 7000000
3755 rows × 2 columns
python jupyter-notebook data-analysis
2个回答
0
投票

从错误中我可以看到您提供的代码与您运行的代码不对应。第 2 行发生错误。我假设您使用的是笔记本,因此运行单元格的顺序很重要。要么给我们单元格,要么尝试复制您在单个单元格中提供的代码并运行它。


0
投票

有人在评论中帮助我解决了这个问题,这个问题是如此简单和愚蠢 我必须从一开始就使用 df 而不是使用

Data
然后说
df=Data[[...]]
所以正确的应该是第三行中的
df = df[[...]]
和第二行中的
df
而不是
Data
,它的工作原理如下,像这样的简单问题导致整个代码错误,这是为什么计算机愚蠢的一个例子,因为最简单的错误整个代码都不起作用

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