我不能以这种方式子集行:df[0](或任何整数)

2024-04-20 14:14:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我加载了一个csv,然后尝试获取具有行索引号的第一行

import pandas as pd

pkm = pd.read_csv('datasets/pokemon_data.csv')
pkm[0]

但由于某种原因,我得到了这个错误,据我所知,你可以用我的方法来子集

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~/Desktop/ml/ml_env/lib/python3.9/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3079             try:
-> 3080                 return self._engine.get_loc(casted_key)
   3081             except KeyError as err:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 0

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
<ipython-input-6-19c40ecbd036> in <module>
----> 1 X[0]

~/Desktop/ml/ml_env/lib/python3.9/site-packages/pandas/core/frame.py in __getitem__(self, key)
   3022             if self.columns.nlevels > 1:
   3023                 return self._getitem_multilevel(key)
-> 3024             indexer = self.columns.get_loc(key)
   3025             if is_integer(indexer):
   3026                 indexer = [indexer]

~/Desktop/ml/ml_env/lib/python3.9/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3080                 return self._engine.get_loc(casted_key)
   3081             except KeyError as err:
-> 3082                 raise KeyError(key) from err
   3083 
   3084         if tolerance is not None:

KeyError: 0

当我使用.iloc.loc时,我不会遇到任何问题

我使用了熊猫1.1.5和1.2.0,得到了相同的错误

以下是数据的外观: pokemon_data


Tags: csvkeyinselfpandasgetindexas