Select values from dictionary to create new DataFrame column
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 value type_dict
, but the only thing I could think of and didn't work:
>>> 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 every line, or is there a better alternative?
0
source to share
1 answer
You can use here map
:
>>> 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 displayed values. It's also very efficiently implemented (much more so than apply
, for example).
+4
source to share