516

I have a dictionary which looks like this: di = {1: "A", 2: "B"}

I would like to apply it to the col1 column of a dataframe similar to:

     col1   col2
0       w      a
1       1      2
2       2    NaN

to get:

     col1   col2
0       w      a
1       A      2
2       B    NaN

How can I best do this? For some reason googling terms relating to this only shows me links about how to make columns from dicts and vice-versa :-/

ah bon
  • 7,903
  • 7
  • 43
  • 86
TheChymera
  • 15,154
  • 14
  • 50
  • 83

11 Answers11

556

You can use .replace. For example:

>>> df = pd.DataFrame({'col2': {0: 'a', 1: 2, 2: np.nan}, 'col1': {0: 'w', 1: 1, 2: 2}})
>>> di = {1: "A", 2: "B"}
>>> df
  col1 col2
0    w    a
1    1    2
2    2  NaN
>>> df.replace({"col1": di})
  col1 col2
0    w    a
1    A    2
2    B  NaN

or directly on the Series, i.e. df["col1"].replace(di, inplace=True).

Winand
  • 1,615
  • 1
  • 24
  • 43
DSM
  • 319,184
  • 61
  • 566
  • 472
  • 3
    It doesn't work for me when if ```col```` is tuple. The error info is ``` Cannot compare types 'ndarray(dtype=object)' and 'tuple'``` – Pengju Zhao Aug 02 '17 at 04:54
  • 33
    It looks like this doesn't work anymore **at all**, which isn't surprising given the answer was from 4 years ago. This question needs a new answer given how general the operation is... – PrestonH Nov 21 '17 at 17:01
  • 5
    @PrestonH It works perfectly for me. Running: `'3.6.1 |Anaconda custom (64-bit)| (default, May 11 2017, 13:25:24) [MSC v.1900 64 bit (AMD64)]'` – Dan Dec 06 '17 at 09:47
  • 3
    It works for me. But how if I want to replace values in ALL columns? – famargar Jan 03 '18 at 10:52
  • 4
    The only method that worked for me of the answers shown was to do a direct replacement on the Series. Thanks! – Dirigo Mar 09 '18 at 18:17
  • @PengjuZhao is right - `replace` does not work for me when the value to replace are tuples - neither on df nor directly on series. Only `map` worked for me in this case. – GuSuku Dec 14 '18 at 05:27
  • So it looks like they keys in di are the indices of the rows? What if they are values in another column of unique values? For example when col3 (not shown) has the value such and such then col1 is A. – demongolem May 12 '20 at 17:29
  • 1
    I was trying to do `df.replace({"col1": di}, inplace=True)` and I got a `SettingWithCopyWarning`. Your comment about the "directly on the `Series`" helped me. dropping `inplace=True` did the trick – Kots Mar 29 '21 at 08:12
  • You saved my day bro! – Tom Hanks Dec 31 '21 at 01:22
451

map can be much faster than replace

If your dictionary has more than a couple of keys, using map can be much faster than replace. There are two versions of this approach, depending on whether your dictionary exhaustively maps all possible values (and also whether you want non-matches to keep their values or be converted to NaNs):

Exhaustive Mapping

In this case, the form is very simple:

df['col1'].map(di)       # note: if the dictionary does not exhaustively map all
                         # entries then non-matched entries are changed to NaNs

Although map most commonly takes a function as its argument, it can alternatively take a dictionary or series: Documentation for Pandas.series.map

Non-Exhaustive Mapping

If you have a non-exhaustive mapping and wish to retain the existing variables for non-matches, you can add fillna:

df['col1'].map(di).fillna(df['col1'])

as in @jpp's answer here: Replace values in a pandas series via dictionary efficiently

Benchmarks

Using the following data with pandas version 0.23.1:

di = {1: "A", 2: "B", 3: "C", 4: "D", 5: "E", 6: "F", 7: "G", 8: "H" }
df = pd.DataFrame({ 'col1': np.random.choice( range(1,9), 100000 ) })

and testing with %timeit, it appears that map is approximately 10x faster than replace.

Note that your speedup with map will vary with your data. The largest speedup appears to be with large dictionaries and exhaustive replaces. See @jpp answer (linked above) for more extensive benchmarks and discussion.

JohnE
  • 26,433
  • 8
  • 74
  • 99
  • 29
    The last block of code for this answer is certainly not the most elegant, but this answer deserves some credit. It is orders of magnitude faster for large dictionaries and doesn't use up all of my RAM. It remapped a 10,000 line file using a dictionary that had about 9 million entries in half a minute. The `df.replace` function, while tidy and useful for small dicts, crashed after running for 20 minutes or so. – griffinc May 11 '17 at 03:29
  • 1
    Related: [Replace values in a pandas series via dictionary efficiently](https://stackoverflow.com/questions/49259580/replace-values-in-a-pandas-series-via-dictionary-efficiently) – jpp Mar 19 '18 at 21:00
  • @griffinc Thanks for the feedback and note that I have since updated this answer with a much simpler way to do the non-exhaustive case (thanks to @jpp) – JohnE Jul 03 '18 at 10:40
  • Is it correct to state that `map` unlike `replace` changes all values in a column and not only those you are interested in changing? – StatsScared Aug 27 '18 at 18:14
  • @StatsScared Either one will only change the value if it matches the key in the dictionary. Note that `map` + `fillna` as shown above behaves exactly the same as `replace` – JohnE Aug 27 '18 at 18:48
  • 1
    `map` also works on an index where I couldn't figure out a way to do that with `replace` – Max Ghenis Mar 15 '19 at 16:42
  • @JohnE, if the aim is to create a new pandas df column, based on the values of another column. Is it worth using ```map``` over ```merge```? – AlexSB Nov 29 '19 at 17:33
  • 1
    @AlexSB I can't give a completely general answer, but I think map would be much faster and accomplish (I think) the same thing. Generally, merge is going to be slower than other options that do the same thing. – JohnE Nov 29 '19 at 23:51
  • The speed difference is strange to me. Surely `pandas` could be written such that `replace` wraps the `map` code? – timgeb May 28 '20 at 06:39
  • I love this solution, neat and efficient! Thanks. – Snoopy Dec 07 '20 at 02:40
  • The note helped; # If the dictionary does not exhaustively map all entries then non-matched entries are changed to NaNs; map was also faster. – Abhishek Sharma Acharya Jan 18 '21 at 09:00
  • 1
    `.map` is certainly the better way. `.map` on a table with millions of entries runs in a matter of seconds while `.replace` was running for more than an hour. `.map` is the recommended way! – user989762 Jan 13 '22 at 08:26
81

There is a bit of ambiguity in your question. There are at least three two interpretations:

  1. the keys in di refer to index values
  2. the keys in di refer to df['col1'] values
  3. the keys in di refer to index locations (not the OP's question, but thrown in for fun.)

Below is a solution for each case.


Case 1: If the keys of di are meant to refer to index values, then you could use the update method:

df['col1'].update(pd.Series(di))

For example,

import pandas as pd
import numpy as np

df = pd.DataFrame({'col1':['w', 10, 20],
                   'col2': ['a', 30, np.nan]},
                  index=[1,2,0])
#   col1 col2
# 1    w    a
# 2   10   30
# 0   20  NaN

di = {0: "A", 2: "B"}

# The value at the 0-index is mapped to 'A', the value at the 2-index is mapped to 'B'
df['col1'].update(pd.Series(di))
print(df)

yields

  col1 col2
1    w    a
2    B   30
0    A  NaN

I've modified the values from your original post so it is clearer what update is doing. Note how the keys in di are associated with index values. The order of the index values -- that is, the index locations -- does not matter.


Case 2: If the keys in di refer to df['col1'] values, then @DanAllan and @DSM show how to achieve this with replace:

import pandas as pd
import numpy as np

df = pd.DataFrame({'col1':['w', 10, 20],
                   'col2': ['a', 30, np.nan]},
                  index=[1,2,0])
print(df)
#   col1 col2
# 1    w    a
# 2   10   30
# 0   20  NaN

di = {10: "A", 20: "B"}

# The values 10 and 20 are replaced by 'A' and 'B'
df['col1'].replace(di, inplace=True)
print(df)

yields

  col1 col2
1    w    a
2    A   30
0    B  NaN

Note how in this case the keys in di were changed to match values in df['col1'].


Case 3: If the keys in di refer to index locations, then you could use

df['col1'].put(di.keys(), di.values())

since

df = pd.DataFrame({'col1':['w', 10, 20],
                   'col2': ['a', 30, np.nan]},
                  index=[1,2,0])
di = {0: "A", 2: "B"}

# The values at the 0 and 2 index locations are replaced by 'A' and 'B'
df['col1'].put(di.keys(), di.values())
print(df)

yields

  col1 col2
1    A    a
2   10   30
0    B  NaN

Here, the first and third rows were altered, because the keys in di are 0 and 2, which with Python's 0-based indexing refer to the first and third locations.

unutbu
  • 777,569
  • 165
  • 1,697
  • 1,613
  • [``replace``](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.replace.html) is equally good, and maybe a better word for what is happening here. – Dan Allan Nov 27 '13 at 19:06
  • Doesn't the OP's posted target dataframe eliminate the ambiguity? Still, this answer is useful, so +1. – DSM Nov 27 '13 at 20:35
  • @DSM: Oops, you are right there is no possibility of Case3, but I don't think the OP's target dataframe distinguishes Case1 from Case2 since the index values equal the column values. – unutbu Nov 27 '13 at 20:47
  • Like a number of others posted, @DSM's method unfortunately didn't work for me, but @unutbu's case 1 did work. `update()` seems a little kludgy compared to `replace()`, but at least it works. – Geoff Jun 26 '19 at 00:56
13

DSM has the accepted answer, but the coding doesn't seem to work for everyone. Here is one that works with the current version of pandas (0.23.4 as of 8/2018):

import pandas as pd

df = pd.DataFrame({'col1': [1, 2, 2, 3, 1],
            'col2': ['negative', 'positive', 'neutral', 'neutral', 'positive']})

conversion_dict = {'negative': -1, 'neutral': 0, 'positive': 1}
df['converted_column'] = df['col2'].replace(conversion_dict)

print(df.head())

You'll see it looks like:

   col1      col2  converted_column
0     1  negative                -1
1     2  positive                 1
2     2   neutral                 0
3     3   neutral                 0
4     1  positive                 1

The docs for pandas.DataFrame.replace are here.

wordsforthewise
  • 11,271
  • 5
  • 74
  • 108
  • 2
    I never had a problem getting DSM's answer to run and I'd guess given the high vote total most other people didn't either. You might want to be more specific about the problem you are having. Maybe it has to do with your sample data which is different than DSM's? – JohnE Aug 31 '18 at 08:42
  • Hmm, perhaps a versioning issue. Nevertheless, both answers are here now. – wordsforthewise Sep 02 '18 at 01:10
  • 1
    The solution in the accepted answer only works on certain types, [`Series.map()`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html) seems more flexible. – AMC Apr 14 '20 at 18:45
7

Given map is faster than replace (@JohnE's solution) you need to be careful with Non-Exhaustive mappings where you intend to map specific values to NaN. The proper method in this case requires that you mask the Series when you .fillna, else you undo the mapping to NaN.

import pandas as pd
import numpy as np

d = {'m': 'Male', 'f': 'Female', 'missing': np.NaN}
df = pd.DataFrame({'gender': ['m', 'f', 'missing', 'Male', 'U']})

keep_nan = [k for k,v in d.items() if pd.isnull(v)]
s = df['gender']

df['mapped'] = s.map(d).fillna(s.mask(s.isin(keep_nan)))

    gender  mapped
0        m    Male
1        f  Female
2  missing     NaN
3     Male    Male
4        U       U
ALollz
  • 54,844
  • 7
  • 56
  • 77
3

Adding to this question if you ever have more than one columns to remap in a data dataframe:

def remap(data,dict_labels):
    """
    This function take in a dictionnary of labels : dict_labels 
    and replace the values (previously labelencode) into the string.

    ex: dict_labels = {{'col1':{1:'A',2:'B'}}

    """
    for field,values in dict_labels.items():
        print("I am remapping %s"%field)
        data.replace({field:values},inplace=True)
    print("DONE")

    return data

Hope it can be useful to someone.

Cheers

Nico Coallier
  • 657
  • 1
  • 8
  • 21
  • 2
    This functionality is already provided by [`DataFrame.replace()`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html), although I don't know when it was added. – AMC Apr 14 '20 at 18:44
3

You can update your mapping dictionary with missing pairs from the dataframe. For example:

df = pd.DataFrame({'col1': ['a', 'b', 'c', 'd', np.nan]})
map_ = {'a': 'A', 'b': 'B', 'd': np.nan}

# Get mapping from df
uniques = df['col1'].unique()
map_new = dict(zip(uniques, uniques))
# {'a': 'a', 'b': 'b', 'c': 'c', 'd': 'd', nan: nan}

# Update mapping
map_new.update(map_)
# {'a': 'A', 'b': 'B', 'c': 'c', 'd': nan, nan: nan}

df['col2'] = df['col1'].map(dct_map_new)

Result:

  col1 col2
0    a    A
1    b    B
2    c    c
3    d  NaN
4  NaN  NaN
Mykola Zotko
  • 12,250
  • 2
  • 39
  • 53
2

Or do apply:

df['col1'].apply(lambda x: {1: "A", 2: "B"}.get(x,x))

Demo:

>>> df['col1']=df['col1'].apply(lambda x: {1: "A", 2: "B"}.get(x,x))
>>> df
  col1 col2
0    w    a
1    1    2
2    2  NaN
>>> 
U12-Forward
  • 65,118
  • 12
  • 70
  • 89
2

A nice complete solution that keeps a map of your class labels:

labels = features['col1'].unique()
labels_dict = dict(zip(labels, range(len(labels))))
features = features.replace({"col1": labels_dict})

This way, you can at any point refer to the original class label from labels_dict.

dorien
  • 5,107
  • 9
  • 48
  • 102
1

As an extension to what have been proposed by Nico Coallier (apply to multiple columns) and U10-Forward(using apply style of methods), and summarising it into a one-liner I propose:

df.loc[:,['col1','col2']].transform(lambda x: x.map(lambda x: {1: "A", 2: "B"}.get(x,x))

The .transform() processes each column as a series. Contrary to .apply()which passes the columns aggregated in a DataFrame.

Consequently you can apply the Series method map().

Finally, and I discovered this behaviour thanks to U10, you can use the whole Series in the .get() expression. Unless I have misunderstood its behaviour and it processes sequentially the series instead of bitwisely.
The .get(x,x)accounts for the values you did not mention in your mapping dictionary which would be considered as Nan otherwise by the .map() method

louisD
  • 175
  • 1
  • 10
  • _The `.transform()` processes each column as a series. Contrary to `.apply()` which passes the columns aggregated in a DataFrame._ I just tried, `apply()` works fine. There's no need to use `loc` either, this seems overly complex. `df[["col1", "col2"]].apply(lambda col: col.map(lambda elem: my_dict.get(elem, elem)))` should work just fine. _The `.get(x,x)`accounts for the values you did not mention in your mapping dictionary which would be considered as Nan otherwise by the `.map()` method_ You could also use `fillna()` afterwards. – AMC Apr 14 '20 at 18:55
  • _Finally, and I discovered this behaviour thanks to U10, you can use the whole Series in the .get() expression. Unless I have misunderstood its behaviour and it processes sequentially the series instead of bitwisely._ I can't reproduce this, can you elaborate? The identically named variables are likely playing some role here. – AMC Apr 14 '20 at 18:57
0

A more native pandas approach is to apply a replace function as below:

def multiple_replace(dict, text):
  # Create a regular expression  from the dictionary keys
  regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))

  # For each match, look-up corresponding value in dictionary
  return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text) 

Once you defined the function, you can apply it to your dataframe.

di = {1: "A", 2: "B"}
df['col1'] = df.apply(lambda row: multiple_replace(di, row['col1']), axis=1)
Amir Imani
  • 2,506
  • 1
  • 19
  • 23
  • 1
    _A more native pandas approach is to apply a replace function as below_ How is that more "native" (idiomatic?) than the much simpler methods provided by Pandas? – AMC Apr 14 '20 at 18:59