尝试以这种方式访问 pandas 数据帧中的单个元素时出现错误 test_df["LABEL"][0]。以下是有关我如何加载数据的代码片段:
print "reading test set"
test_set = pd.read_csv(data_path+"small_test_products.txt", header=0, delimiter="|")
print "shape of the test set", test_set.shape
test_df = pd.DataFrame(test_set)
lengthOfTestSet = len(test_df["LABEL"])
print test_df["LABEL"][0]
这是我遇到的错误:
File "code.py", line 80, in <module>
print test_df["LABEL"][0]
File "/usr/local/lib/python2.7/dist-packages/pandas/core/series.py", line 521, in __getitem__
result = self.index.get_value(self, key)
File "/usr/local/lib/python2.7/dist-packages/pandas/core/index.py", line 3562, in get_value
loc = self.get_loc(k)
File "/usr/local/lib/python2.7/dist-packages/pandas/core/index.py", line 3619, in get_loc
return super(Float64Index, self).get_loc(key, method=method)
File "/usr/local/lib/python2.7/dist-packages/pandas/core/index.py", line 1572, in get_loc
return self._engine.get_loc(_values_from_object(key))
File "pandas/index.pyx", line 134, in pandas.index.IndexEngine.get_loc (pandas/index.c:3824)
File "pandas/index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas/index.c:3704)
File "pandas/hashtable.pyx", line 541, in pandas.hashtable.Float64HashTable.get_item (pandas/hashtable.c:9914)
File "pandas/hashtable.pyx", line 547, in pandas.hashtable.Float64HashTable.get_item (pandas/hashtable.c:9852)
KeyError: 0.0
我错过了什么?
请您参考如下方法:
正如 EdChum 所说,0 可能不在您的索引中。
尝试:df.iloc[0] 或 df['label'].iloc[0],这是基于整数的位置。
如果遇到问题,重置索引:df.reset_index(drop=True)
查看 Pandas 的 indexing doc了解更多信息
