简体   繁体   English

我不能以这种方式对 pandas 中的行进行子集化:df[0](或任何整数)

[英]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我加载了 csv 然后尝试获取具有行索引号的第一行

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当我使用.iloc.loc时,我不会遇到任何问题

I used pandas 1.1.5 and 1.2.0 and I got the same error我使用了 pandas 1.1.5 和 1.2.0,我得到了同样的错误

This is how the data looks: pokemon_data这是数据的样子: pokemon_data

pkm[0] calls for the column named 0 in pkm . pkm[0]调用pkm中名为0的列。 That's why it's not working.这就是为什么它不起作用。 Try pkm['HP'] or using a column name and it will be clear.尝试pkm['HP']或使用列名,它会很清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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