问题描述
我一直在使用熊猫处理数据框,在清理这些数据时,我在迭代时遇到了问题...
例如(我试图找出错误的地方):
N_index = df.shape[0]
j = 0
while j < N_index:
print(j,df.diag_1[j][0],'squalala')
j += 1
此显示此:
0 2 squalala
1 2 squalala
2 6 squalala
3 8 squalala
4 1 squalala
5 4 squalala
6 4 squalala
7 4 squalala
8 3 squalala
9 4 squalala
10 2 squalala
11 1 squalala
12 4 squalala
13 4 squalala
14 5 squalala
15 9 squalala
16 4 squalala
17 6 squalala
18 4 squalala
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/pandas/core/indexes/base.py in get_loc(self,key,method,tolerance)
2890 try:
-> 2891 return self._engine.get_loc(casted_key)
2892 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.Int64HashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()
KeyError: 19
由于第18个索引之后的某些原因(idk哪个),它无法工作,因此,如果您对如何解决它或为什么要这样做有任何想法,我将非常感激您。
PS。我在exmaple上使用的是while循环,而不是for循环,但是我尝试了两者,因为我在另一个Stack Overflow帖子上看到这解决了他们的问题,对我而言,它不是^^
PSS。我正在使用笔记本
编辑:这里我正在做df.diag_1[j][0]
,因为我想访问数据帧的diag_1列中第j行的字符串的第一个元素–
解决方法
KeyError:19表示程序正在尝试获取第19个元素,但它不存在。
您可以尝试直接打印df吗?我怀疑第19行的索引不是19。要重置索引,可以执行以下操作:
df.reset_index(drop=True)
,
也许其他地方有问题,索引应该可以工作,请参阅:
df = pd.DataFrame({"one":["1X","2Y","3Z"]})
N_index = df.shape[0]
j=0
while j < N_index:
print(j,df.one[j][0])
j += 1
要确保索引能按预期工作,只需在尝试查找循环中的行之前重设索引即可:
df.reset_index()
这里是一个示例,当您索引的不是标准0到N-1行时:
df = pd.DataFrame({"one":["1X","3Z"]})
df['new_index'] = range(2,5)
df = df.set_index("new_index")
print(df)
# reset the index to make your loop work
df=df.reset_index()
N_index = df.shape[0]
j=0
while j < N_index:
print(j,df.one[j][0])
j += 1
注意,通常来说,不需要像您一样遍历熊猫数据框,例如,可以使用apply方法,例如:
out= df.one.apply(lambda x:x[1])
将在每一行中为您提供字符串的第二个元素。以大熊猫文件为例:10-minutes to pandas;或此处涉及索引的多个问题。
,我的调查一直在进行,仅当我做df.head(25)
时,我就能看到不同的索引:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 22 23 24 25 26 27
如您所见,从19到21的索引丢失了(很可能是先前做过的dropna()
的索引。因此,错误可能来自此处,因为您所提到的那些索引不存在。 / p>
所以我可以通过以下方式访问现有索引:
for j in df.index:
print(j,df.diag_1[j][0]):
这解决了问题。