请帮助我解决Python数据帧中的此关键错误?

问题描述 投票:0回答:1

我想知道是否有人可以帮助我解决以下错误:

 **raise KeyError("{} not found in axis".format(labels[mask]))
KeyError: '[18] not found in axis'**

我正在尝试根据条件删除行,而我的代码如下:

PSE2=PSE1

for i in range(1,len(PSE1)):
    if PSE1.iloc[[i],[1]].values==PSE1.iloc[[i+1],[1]].values or PSE1.iloc[[i],[1]].values==PSE1.iloc[[i-1],[1]].values:
        pass
    else:
        print(str(i))
        print(PSE2.iloc[[i],[1]].values)
        PSE2=PSE2.drop([i],axis=0)

PSE1和PSE2是两个相同的数据帧。

python dataframe keyerror
1个回答
1
投票

问题可能出在if条件下的[i+1]。在循环的最后一步,请输入i = len(PSE1) - 1,以便PSE1.iloc[[i+1],[1]]存在

for i in range(1,len(PSE1)):
    if PSE1.iloc[[i],[1]].values==PSE1.iloc[[i+1],[1]].values

为解决这个问题,您可以用[:]替换您的if条件:>

if PSE1.iloc[[i],[1]].values==PSE1.iloc[[i-1],[1]].values or
i < len(PSE1)-1 and
PSE1.iloc[[i],[1]].values==PSE1.iloc[[i+1],[1]].values:
© www.soinside.com 2019 - 2024. All rights reserved.