Search code examples
pythondataframekeyerror

How to fix this KeyError? KeyError: 'PID' (Python language)


The "PID" is in the DataFrame tbh. The screen capture shows the problem and my code lines. See image I tried to restart my kernel, but the error still occurred...


Solution

  • Instead of using df.apply(get_party), just use df.PID.apply(get_party) with pid as a parameter of get_party function.

    def get_party(pid):
      if pid < 2.0:
        return 'Democrat'
      elif pid == 5.0 or pid == 6.0:
        return 'republication'
      else:
        return 'Independent'
    
    df['party'] = df.PID.apply(get_party)