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

Question:

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…

Asked By: Silencieuse

||

Answers:

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)
Answered By: Jordy
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.