Dictionary lookup causing objects are mutable, thus they cannot be hashed error

2.4k views Asked by At

I have a python dict/hashmap:

yearMapping = {"2016":"6", "2017":"7", "2018":"8", "2019":"9"}

I am trying to replace values within a DataFrame object with the corresponding map value. I wrote out an example below with my expected output.

I have 3 columns with data in them. If generated code is null, I am going to populate that column with the Contract Time + the map value.

Generated Code      |      Contract Date      |     Contract Time
    null            |         201607          |          1:31:01

Expected output:

Generated Code      |      Contract Date      |     Contract Time
    1:31:016        |         201607          |          1:31:01

What I am doing so far:

yearCode = df['Contract Date'].astype(str).apply(lambda x: x[:4])

df.loc[df["Generated Code"].isnull(),'Generated Code'] = df['Contract Time'] + yearMapping.get(yearCode)

I keep getting the error: TypeError: 'Series' objects are mutable, thus they cannot be hashed

Is this even do-able?

1

There are 1 answers

0
jezrael On BEST ANSWER

I think you need replace from null to NaN, then indexing with str and last Series yearCode map by dict:

df['Generated Code'] = df['Generated Code'].replace({'null':np.nan})

yearMapping = {"2016":"6", "2017":"7", "2018":"8", "2019":"9"}

yearCode = df['Contract Date'].astype(str).str[:4]

df.loc[df["Generated Code"].isnull(),'Generated Code'] = 
df['Contract Time'] + yearCode.map(yearMapping)
print (df)
  Generated Code  Contract Date Contract Time
0       1:31:016         201607       1:31:01

Another solution is change condition:

yearMapping = {"2016":"6", "2017":"7", "2018":"8", "2019":"9"}
yearCode = df['Contract Date'].astype(str).str[:4]
df.loc[df["Generated Code"] == 'null','Generated Code'] = 
df['Contract Time'] + yearCode.map(yearMapping)
print (df)
  Generated Code  Contract Date Contract Time
0       1:31:016         201607       1:31:01