使用CSV文件时在Jupyter Notebook中出现KeyError
我在Kaggle上找到了一个CSV文件,所以我下载了它来学习。我导入了pandas模块,然后用它读取了这个文件。接着,我只保留了薪水和薪水货币这两列。然后我想找出以美元(USD)为货币的最高和最低薪水,但我尝试使用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
2 个回答
0
有人在评论里帮我解决了这个问题,问题其实很简单也很傻。我一开始应该直接用 df
,而不是先用 Data
,然后再写 df=Data[[...]]
。正确的写法应该是第三行用 df = df[[...]]
,第二行用 df
而不是 Data
。这样一来,代码就能正常运行了。像这样的小问题就能把整个代码搞错,这就是为什么说电脑傻,因为最简单的错误就能让整个代码不工作。
0
从错误信息来看,你提供的代码和你实际运行的代码不一致。错误发生在第二行。我猜你是在用笔记本,所以你运行单元格的顺序很重要。要么把所有单元格给我们,要么试着把你提供的代码放在一个单元格里运行。