Home > OS >  pandas.df.replace returning a TypeError: Unhashable type: 'list'
pandas.df.replace returning a TypeError: Unhashable type: 'list'

Time:07-07

I'm trying to convert multiple values within one column to a string value with pandas:

ort_raw['Location'] = ort_raw['Location'].replace({['1', 1]:['remote'],
                                                   ['0',0]:['in_lab']})

...where ort_raw is the df, 'Location' is a particular column name, and 1 as a string or int must be 'remote' while 0 as a string or int must be 'in_lab'. This chunk returns the following error:

TypeError: unhashable type: 'list'

Thanks for any help!

CodePudding user response:

IIUC, use a unique key for each possibly.

ort_raw['Location'] = ort_raw['Location'].replace({'1': 'remote', 1: 'remote', '0': 'in_lab', 0: 'in_lab'})

If you want to compress a bit:

d = {'remote': [1, '1'], 'in_lab': [0, '0']}
ort_raw['Location'] = ort_raw['Location'].replace({k:v for v,l in d.items() for k in l})

NB. In this particular case, you could also convert to string and only use the string key.

ort_raw['Location'] = ort_raw['Location'].replace({'1': 'remote', '0': 'in_lab'})

CodePudding user response:

The issue is with the dictionary. Keys can't be lists.

you need to have separate keys for the integers and strings.

to_replace = {'1': 'remote', 1: 'remote', '0': 'in_lab', 0: 'in_lab'}
ort_raw['Location'] = ort_raw['Location'].replace(to_replace)
  • Related