1

I have a dictionary

type_dict = {3: 'foo', 4: 'bar',5: 'foobar', 6: 'foobarbar'}

and a DataFrame with the following column:

>>> df.type
0     3
1     4
2     5
3     6
4     3
5     4
6     5
7     6
8     3

I want to create a new column containing the corresponding type_dict value, but the following was the only thing I could come up and was not working:

>>> type_dict[df.type]
TypeError: 'Series' objects are mutable, thus they cannot be hashed

>>> type_dict[df.type.values]
TypeError: unhashable type: 'numpy.ndarray'

Do I really need to apply and iterate through each row, or is there a more efficient alternative?

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
FooBar
  • 15,724
  • 19
  • 82
  • 171

1 Answers1

5

You could use map here:

>>> df['type'].map(type_dict)
0          foo
1          bar
2       foobar
3    foobarbar
4          foo
5          bar
6       foobar
7    foobarbar
8          foo
Name: type, dtype: object

map can take a dictionary, Series or function and return a new Series with the mapped values. It is also very efficiently implemented (much more so than apply, for example).

Alex Riley
  • 169,130
  • 45
  • 262
  • 238