Pandas KeyError('%s not in index' % objarr[mask]) 对我来说,但不是其他具有相同代码的人



我收到这个错误,我的教授没有收到,运行他为我们类提供的相同示例代码。 我在这里或 Anaconda 或 Python Tutor 列表中都没有找到解决方案。

我们正在学习基本的python,查看最简单的Pandas DataFrames并学习选择列。 我们构建了一个数据帧 df(5 行,5 列),除了一行代码外,其他所有代码都可以正常工作。 不起作用的行是:

df[ [0,1] ]

在我的系统上,它不断地在df[ [0,1] ]命令上抛出这个KeyError。 我得到df[ [0] ]df[ [1] ]的类似错误.

Traceback (most recent call last):
File "<ipython-input-7-c392a914e584>", line 1, in <module>
df[ [0,1] ]
File "C:UsersxxxxAppDataLocalContinuumanaconda3libsite-packagespandascoreframe.py", line 1958, in __getitem__
return self._getitem_array(key)
File "C:UsersxxxxAppDataLocalContinuumanaconda3libsite-packagespandascoreframe.py", line 2002, in _getitem_array
indexer = self.loc._convert_to_indexer(key, axis=1)
File "C:UsersxxxxAppDataLocalContinuumanaconda3libsite-packagespandascoreindexing.py", line 1231, in _convert_to_indexer
raise KeyError('%s not in index' % objarr[mask])
KeyError: '[0 1] not in index'

对我来说,这感觉就像是关于Python如何安装在我的计算机上的东西。 我有 Anaconda Navigator 1.7.0 安装在 64 位 Win 7 Pro 下。 我已经多次直接重新启动Anaconda和Sypder,并在许多天内重新启动了很多次。 同样的错误。 我今天更新了蟒蛇。 同样的错误。 我正在通过 anaconda 导航器或直接从开始菜单运行 spyder - 同样的错误。 正如我之前提到的,我的教授运行相同的代码没有问题。

有没有人对这一件事在我的计算机上不起作用有什么问题有任何建议? 下面的代码示例包括我能够在机器上执行的其他几个列选择,因此我认为数据帧通常可以工作。

我注意到的一件事是,由于这台PC的设置方式,我的路径很长。 我想知道这是否可能是问题的一部分。

示例代码 - 来自教授,对他有用,除了最后一行之外,其他所有代码对我来说也很好。

#%%
import pandas
#%% data frame from dictionary
raw_data = {'first_name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
'last_name': ['Miller', 'Jacobson', ".", 'Milner', 'Cooze'],
'age': [42, 52, 36, 24, 73],
'preTestScore': [4, 24, 31, ".", "."],
'postTestScore': [25, 94, 57, 62, 70]}

df = pandas.DataFrame(raw_data, columns = ['first_name', 'last_name', 'age', 'preTestScore', 'postTestScore'])
df
#%% select the 'first_name' column
b =df['first_name']
b.tolist()
#%% select multiple columns
df[ ['first_name', 'last_name'] ]

#%% select the first 2 columns (by column index - FAILS FOR ME)
# (THIS IS THE LINE THAT THROWS THE ERROR LISTED ABOVE)
df[ [0,1] ]

我尝试过的其他代码 - 这些也有效。

#%% prove that the columns are there
print(df.columns)
#%% select multiple columns by column name
b = df[ ['first_name', 'last_name'] ]
print(b)
#%% select same columns by sub-setting column list
c = df[ df.columns[0:2] ]
print(c)

关于如何解决这个问题的任何想法?我能提供任何其他信息来提供帮助吗? 提前谢谢。

检查两台机器中的熊猫版本。

import pandas as pd
pd.__version__

相关内容

最新更新