Python 筛选后在数据帧中获取KeyError

Python 筛选后在数据帧中获取KeyError,python,pandas,dataframe,Python,Pandas,Dataframe,在应用列式选择后,我尝试访问pandas数据框中的一行。但是,它在过滤数据帧中存在的某些行索引(这里是行索引2,尽管我可以访问行3)上给出了一个错误。请有人解释一下,并帮助我找到一个解决方法,以便我可以在正常的索引流(即0,1,2…)中访问数据帧。提前谢谢 >>> import pandas as pd >>> a = pd.read_csv("sample.csv") >>> a Col1 Col2 Col3

在应用列式选择后,我尝试访问pandas数据框中的一行。但是,它在过滤数据帧中存在的某些行索引(这里是行索引2,尽管我可以访问行3)上给出了一个错误。请有人解释一下,并帮助我找到一个解决方法,以便我可以在正常的索引流(即0,1,2…)中访问数据帧。提前谢谢

>>> import pandas as pd
>>> a = pd.read_csv("sample.csv")
>>> a
   Col1  Col2  Col3
0     1     2     1
1     5     9     1
2     6     9     0
3     2     7     1
>>> a = a[a['Col3']>0]
>>> a
   Col1  Col2  Col3
0     1     2     1
1     5     9     1
3     2     7     1
>>> a['Col1'][0]
1
>>> a['Col1'][2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/dist-packages/pandas/core/series.py", line 767, in __getitem__
    result = self.index.get_value(self, key)
  File "/usr/local/lib/python3.6/dist-packages/pandas/core/indexes/base.py", line 3118, in get_value
    tz=getattr(series.dtype, 'tz', None))
  File "pandas/_libs/index.pyx", line 106, in pandas._libs.index.IndexEngine.get_value
  File "pandas/_libs/index.pyx", line 114, in pandas._libs.index.IndexEngine.get_value
  File "pandas/_libs/index.pyx", line 162, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 958, in pandas._libs.hashtable.Int64HashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 964, in pandas._libs.hashtable.Int64HashTable.get_item
KeyError: 2
>>> a['Col1'][1]
5
>>> a['Col1'][3]
2
>>将熊猫作为pd导入
>>>a=pd.read\u csv(“sample.csv”)
>>>a
Col1 Col2 Col3
0     1     2     1
1     5     9     1
2     6     9     0
3     2     7     1
>>>a=a[a['Col3']>0]
>>>a
Col1 Col2 Col3
0     1     2     1
1     5     9     1
3     2     7     1
>>>a['Col1'][0]
1.
>>>a['Col1'][2]
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“/usr/local/lib/python3.6/dist-packages/pandas/core/series.py”,第767行,在__
结果=self.index.get_值(self,key)
文件“/usr/local/lib/python3.6/dist packages/pandas/core/index/base.py”,第3118行,在get_值中
tz=getattr(series.dtype,'tz',无))
文件“pandas/_libs/index.pyx”,第106行,在pandas._libs.index.IndexEngine.get_值中
文件“pandas/_libs/index.pyx”,第114行,在pandas._libs.index.IndexEngine.get_值中
文件“pandas/_libs/index.pyx”,第162行,在pandas._libs.index.IndexEngine.get_loc中
文件“pandas/_libs/hashtable_class_helper.pxi”,第958行,在pandas._libs.hashtable.Int64HashTable.get_项中
文件“pandas/_libs/hashtable_class_helper.pxi”,第964行,在pandas._libs.hashtable.Int64HashTable.get_项中
关键错误:2
>>>a['Col1'][1]
5.
>>>a['Col1'][3]
2.

您可以使用
.iat[]

a = a[a['Col3']>0]
print(a)
print(a['Col1'].iat[2])  # prints 2
印刷品:

   Col1  Col2  Col3
0     1     2     1
1     5     9     1
3     2     7     1
2

您可以使用
iloc
进行纯粹基于整数的索引:

a = pd.DataFrame({'Col1':[1,5,6,2],'Col2':[2,9,9,7],'Col3':[1,1,0,1]})
a = a[a['Col3']>0]
a.iloc[2]

Col1    2
Col2    7
Col3    1