Search code examples
pythonpandasdataframespyderkeyerror

Why does this ID generating code make a KeyError: -1


A problem in this part of my code causes KeyError: -1

Do any of you know what might cause this?

for i in range(len(B130317)):
    if B130317['LON'][i] != B130317['LON'][i-1]:
        currentID += 1
    newID.append(currentID)

Solution

  • based on the comments of @Badgy:

    for i in range(1,len(B130317)):
        if B130317['LON'][i] != B130317['LON'][i-1]:
            currentID += 1
        newID.append(currentID)
    

    or:

    for i in range(len(B130317)-1):
        if B130317['LON'][i] != B130317['LON'][i+1]:
            currentID += 1
        newID.append(currentID)