Skip to content Skip to sidebar Skip to footer

Select Values From Dictionary To Create A 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

Solution 1:

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).

Post a Comment for "Select Values From Dictionary To Create A New Dataframe Column"