导致对象可变的字典查找,因此它们不能被散列错误

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

我有一个 python dict/hashmap:

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

我正在尝试用相应的地图值替换 DataFrame 对象中的值。我在下面用我的预期输出写了一个例子。

我有 3 列,其中包含数据。如果生成的代码为空,我将用合同时间 + 地图值填充该列。

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

预期输出:

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

目前我在做什么:

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)

我不断收到错误消息:TypeError:'Series' 对象是可变的,因此无法对它们进行哈希处理

这甚至可行吗?

我认为你需要 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

另一个解决方案是改变条件:

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