Home > Enterprise >  Python dictionary.get TypeError: unhashable type: 'Series'
Python dictionary.get TypeError: unhashable type: 'Series'

Time:03-17

I am trying to get a error here and don't know how to properly fix it. my dictionary is like this below.

dict_wu = {'1004': 'UG', '1028': 'MG', '1043': 'MG', '2801': 'UG', '2802': 'UG', '2803': 'MG'}

my dataframe is like below:

    AC      Units
2   1002    UG
3   1004    MG
6   1004    UG
7   1005    UG
..   ..     ..
91  1028    MG
92  1028    UG
93  1028    UG

I tried to make a series by s = dict_wu.get(df['AC'].astype(str))

Traceback (most recent call last): File "f:...\pull_differences.py", line 35, in s= dict_wu.get(df['AC'].astype(str)) TypeError: unhashable type: 'Series'

How do I fix this? How would I test conditions of two columns to create a new column like below?

df['test'] = np.where(dict_wu.get(df['AC'].astype(str)) == df['Units'] ,True ,False)

CodePudding user response:

pd.Series.map is perfect for this.

df['AC'].astype(str).map(dict_wu)

In conjunction with your other code:

df['test'] = np.where(df['AC'].astype(str).map(dict_wu) == df['Units'], True, False)

Output:

>>> df
      AC Units   test
2   1002    UG  False
3   1004    MG  False
6   1004    UG   True
7   1005    UG  False
91  1028    MG   True
92  1028    UG  False
93  1028    UG  False
  • Related