So I am trying to rename the unemply_states.columns to the names in the dictionary (id_to_state), but I keep getting the error shown. I don’t know if this is a factor but the two have different data types.
The code with the error is:
[id_to_state[c] for c in unemply_states.columns]
The error is:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[123], line 1
----> 1 [id_to_state[c] for c in unemply_states.columns]
KeyError: 0
I have tried changing the data type of the columns to object to match the dictionary but the error persists.
The code to change the columns which are integers to object is:
def convert_int_column_names_to_str(unemply_states):
# Convert integer column names to strings
unemply_states.columns = unemply_states.columns.map(str)
return unemply_states
Which still returns the value as integers as opposed to object.
Brian Coding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Either use get
to handle missing keys:
unemply_states.columns = [id_to_state.get(c, c) for c in unemply_states.columns]
or better rename
:
unemply_states = unemply_states.rename(columns=id_to_state)