Python dictionary.get TypeError: unhashable type: 'Series'

Question:

I am trying to figure this out but I am 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)
Asked By: Shane S

||

Answers:

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
Answered By: user17242583
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.