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…
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)
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…
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)