简体   繁体   中英

I can't subset rows in pandas this way: df[0] (or with any integer)

I loaded a csv and then tried to get the first row with the row index number

import pandas as pd

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

But for some reason I get this error, as far as I know, you can subset the way I did.

---------------------------------------------------------------------------
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

When I use .iloc or .loc I don't face any issues

I used pandas 1.1.5 and 1.2.0 and I got the same error

This is how the data looks: pokemon_data

pkm[0] calls for the column named 0 in pkm . That's why it's not working. Try pkm['HP'] or using a column name and it will be clear.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM