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

Answer from DSM on Stack Overflow
🌐
DataCamp
campus.datacamp.com › courses › writing-efficient-code-with-pandas › replacing-values-in-a-dataframe
Replace values using dictionaries | Python
The syntax is very simple: we map each value we want to replace to the value we want to replace it with, using the colon symbol. We could do the same thing with lists, but it's a more verbose. If we compare both methods, we can see that dictionaries run approximately 55% faster.
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.replace.html
pandas.DataFrame.replace — pandas 3.0.6 documentation
Dicts can be used to specify different replacement values for different existing values. For example, {'a': 'b', 'y': 'z'} replaces the value ‘a’ with ‘b’ and ‘y’ with ‘z’. To use a dict in this way, the optional value parameter should not be given.
Discussions

python - Remap values in pandas column with a dict, preserve NaNs - Stack Overflow
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 ... More on stackoverflow.com
🌐 stackoverflow.com
python - using dict to replace values in a pandas column - Stack Overflow
Also if you read the documents associated with replacing you would see the information around dictionaries and replacement.: 2021-05-25T13:23:38.76Z+00:00 ... Not sure what's wrong, perhaps you have syntax (missing parens or brackets) issues or a different pandas version. More on stackoverflow.com
🌐 stackoverflow.com
python - Use dictionary to replace a string within a string in Pandas columns - Stack Overflow
I am trying to use a dictionary ... in a pandas column with its values. However, each column contains sentences. Therefore, I must first tokenize the sentences and detect whether a Word in the sentence corresponds with a key in my dictionary, then replace the string with the corresponding value. However, the result that I continue to get it none. Is there a better pythonic way to approach ... More on stackoverflow.com
🌐 stackoverflow.com
Replacing words in Pandas series using a dictionary
You could use a nested for loop with enumerate() in the inner loop: reviews = [['bad', 'movie', 'it', 'was', 'turrible'],['bad', 'acting', 'in', 'it'], ['ok', 'experience']] d = {'turrible':'terrible', 'ok':'okay'} for sub in reviews: for i, word in enumerate(sub): if word in d: sub[i] = d[word] >>> reviews [['bad', 'movie', 'it', 'was', 'terrible'], ['bad', 'acting', 'in', 'it'], ['okay', 'experience']] I've just noticed there is a comma missing between 'in' and 'it' in reviews[1] :) More on reddit.com
🌐 r/learnpython
8
2
December 30, 2017
🌐
Reddit
reddit.com › r/learnpython › replace column using a dictionary and df.replace()
r/learnpython on Reddit: Replace column using a dictionary and df.replace()
November 29, 2021 -

Hi there,

I'm trying to replace values in a dataframe column with others using a dictionary and replace, but when I try the code below, the replaced values look completely wrong!

data_humidity = data_season.copy()

replace_vals={'30%-70%':50,'<30%':15,'>70%':85,'NaN':'NaN'}

data_humidity['Humidity(%)'] = data_humidity.replace({'Humidity(%): replace_vals'})

data_humidity['Humidity(%)']

Can someone point me to where I'm going wrong?

Many thanks

🌐
Saturn Cloud
saturncloud.io › blog › how-to-use-a-dictionary-to-replace-column-values-on-given-index-numbers-on-a-pandas-dataframe
How to Use a Dictionary to Replace Column Values on Given Index Numbers on a Pandas Dataframe | Saturn Cloud Blog
January 8, 2024 - The keys in the dictionary should be the index numbers of the values you want to replace, and the values should be the new values you want to replace them with. For example, suppose we have the following dataframe: import pandas as pd data = {'name': ['Alice', 'Bob', 'Charlie'], 'age': [25, 30, 35], 'gender': ['F', 'M', 'M']} df = pd.DataFrame(data) print(df)
🌐
Spark By {Examples}
sparkbyexamples.com › home › pandas › pandas remap values in column with a dictionary (dict)
Pandas Remap Values in Column with a Dictionary (Dict) - Spark By {Examples}
December 10, 2024 - We are often required to remap a Pandas DataFrame column values with a dictionary (Dict), you can achieve this by using the DataFrame.replace() method.
Top answer
1 of 12
628

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

2 of 12
603

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.

🌐
GeeksforGeeks
geeksforgeeks.org › using-dictionary-to-remap-values-in-pandas-dataframe-columns
Using dictionary to remap values in Pandas DataFrame columns - GeeksforGeeks
March 22, 2025 - One common transformation is remapping values using a dictionary. This technique is useful when we need to replace categorical values with labels, abbreviations or numerical representations.
Find elsewhere
🌐
pandas
pandas.pydata.org › pandas-docs › dev › reference › api › pandas.DataFrame.replace.html
pandas.DataFrame.replace — pandas 3.2.0.dev0 documentation
If value is not None and to_replace is a dictionary, the dictionary keys will be the DataFrame columns that the replacement will be applied.
🌐
Pandas
pandas.pydata.org › pandas-docs › version › 2.1 › reference › api › pandas.DataFrame.replace.html
pandas.DataFrame.replace — pandas 2.1.4 documentation
Dicts can be used to specify different replacement values for different existing values. For example, {'a': 'b', 'y': 'z'} replaces the value ‘a’ with ‘b’ and ‘y’ with ‘z’. To use a dict in this way, the optional value parameter should not be given.
Top answer
1 of 2
45

You can create dictionary and then replace:

ids = {'Id':['NYC','LA','UK'],
      'City':['New York City','Los Angeles','United Kingdom']}

ids = dict(zip(ids['Id'], ids['City']))
print (ids)
{'UK': 'United Kingdom', 'LA': 'Los Angeles', 'NYC': 'New York City'}

df['commentTest'] = df['Comment'].replace(ids, regex=True)
print (df)
  Categories                       Comment  Type  \
0     animal      The NYC tree is very big  tree   
1      plant  The cat from the UK is small   dog   
2     object     The rock was found in LA.  rock   

                                commentTest  
0        The New York City tree is very big  
1  The cat from the United Kingdom is small  
2        The rock was found in Los Angeles.  
2 of 2
15

It's actually much faster to use str.replace() than replace(), even though str.replace() requires a loop:

ids = {'NYC': 'New York City', 'LA': 'Los Angeles', 'UK': 'United Kingdom'}

for old, new in ids.items():
    df['Comment'] = df['Comment'].str.replace(old, new, regex=False)

#   Categories  Type                                   Comment
# 0     animal  tree        The New York City tree is very big
# 1      plant   dog  The cat from the United Kingdom is small
# 2     object  rock         The rock was found in Los Angeles

The only time replace() outperforms a str.replace() loop is with small dataframes:

The timing functions for reference:

def Series_replace(df):
    df['Comment'] = df['Comment'].replace(ids, regex=True)
    return df

def Series_str_replace(df):
    for old, new in ids.items():
        df['Comment'] = df['Comment'].str.replace(old, new, regex=False)
    return df

Note that if ids is a dataframe instead of dictionary, you can get the same performance with itertuples():

ids = pd.DataFrame({'Id': ['NYC', 'LA', 'UK'], 'City': ['New York City', 'Los Angeles', 'United Kingdom']})

for row in ids.itertuples():
    df['Comment'] = df['Comment'].str.replace(row.Id, row.City, regex=False)
🌐
Reddit
reddit.com › r/learnpython › replacing words in pandas series using a dictionary
r/learnpython on Reddit: Replacing words in Pandas series using a dictionary
December 30, 2017 -

I have a tokenized pandas Series that looks like this:

reviews = [['bad', 'movie', 'it', 'was', 'turrible'],['bad', 'acting', 'in' 'it'], ['ok', 'experience'],...]

I have a dictionary like this:

d = {'turrible':'terrible', 'ok':'okay',...}

Any words in the reviews that appear in the dictionary keys should be replaced with the dictionary values. So the expected output is:

reviews = [['bad', 'movie', 'it', 'was', 'terrible'],['bad', 'acting', 'in', 'it'], ['okay', 'experience'],...]

I've searched for hours, and I've tried these solutions, but I am not getting the expected output.

Trial 1:

pattern = re.compile(r'\b(' + '|'.join(d.keys()) + r')\b') result = pattern.sub(lambda x: d[x.group()], reviews)

Output: error: incomplete escape \u

Trial 2:

def replaceWords(text,wdict): return ''.join(wdict.get(word,word) for word in text) replaceWords(docs,d) Output: TypeError unhashable type: 'list'

Trial 3 - no error message but did not get expected output:

reviews = reviews.replace(d)

Trial 4:

reviews = reviews.replace(d, regex=True) error: missing ), unterminated subpattern

Any help would be appreciated.

🌐
Pandas
pandas.pydata.org › pandas-docs › version › 1.0.5 › reference › api › pandas.DataFrame.replace.html
pandas.DataFrame.replace — pandas 1.0.5 documentation
Dicts can be used to specify different replacement values for different existing values. For example, {'a': 'b', 'y': 'z'} replaces the value ‘a’ with ‘b’ and ‘y’ with ‘z’. To use a dict in this way the value parameter should be None.
🌐
w3resource
w3resource.com › python-exercises › pandas › pandas-replace-values-in-series-using-map-and-dictionary-mapping.php
Pandas - Replace values in Series using map and dictionary mapping
import pandas as pd # Create a sample Series s = pd.Series([1, 2, 3, 4, 5]) # Define a dictionary to map values replace_dict = {1: 'one', 2: 'two', 3: 'three'} # Apply the dictionary mapping using map() s_mapped = s.map(replace_dict) # Output ...
🌐
GitHub
github.com › pandas-dev › pandas › issues › 46606
BUG: DataFrame.replace with dict doesn't work when value=None · Issue #46606 · pandas-dev/pandas
April 1, 2022 - import pandas as pd df = pd.DataFrame(dict(a=[1,2,3], b=[1,2,3])) df.replace({1:5}, value=None) # does not replace values at all df.replace({1:5}) # correctly replaces 1s with 5s
Author: pandas-dev
🌐
CSDN
devpress.csdn.net › python › 6304579ec67703293080b7fb.html
Use dictionary to replace a string within a string in Pandas columns_python_Mangs-Python
August 23, 2022 - ids = {'Id':['NYC','LA','UK'], 'City':['New York City','Los Angeles','United Kingdom']} ids = dict(zip(ids['Id'], ids['City'])) print (ids) {'UK': 'United Kingdom', 'LA': 'Los Angeles', 'NYC': 'New York City'} df['commentTest'] = df['Comment'].replace(ids, regex=True) print (df) Categories Comment Type \ 0 animal The NYC tree is very big tree 1 plant The cat from the UK is small dog 2 object The rock was found in LA. rock commentTest 0 The New York City tree is very big 1 The cat from the United Kingdom is small 2 The rock was found in Los Angeles. ... 问题:如何重塑熊猫。系列 在我看来,它就像 pandas.Series 中的一个错误。 a = pd.Series([1,2,3,4]) b = a.reshape(2,2) b b 有类型 Series 但无法显示,最后一条语句给出异常,非常冗长,最后一行是“TypeError: %d format: a number is required, not numpy.ndarray”。 b.sha
Top answer
1 of 1
10

UPDATE:

In [108]: data
Out[108]:
   id                  text
0   1  acclrtr actn corr cr
1   2   plate corr affinity   # NOTE: `affinity`
2   3              alrm alt

In [109]: d2 = {r'(\b){}(\b)'.format(k):r'\1{}\2'.format(v) for k,v in d.items()}

In [110]: d2
Out[110]:
{'(\\b)acclrtr(\\b)': '\\1accelerator\\2',
 '(\\b)actn(\\b)': '\\1action\\2',
 '(\\b)aff(\\b)': '\\1affinity\\2',
 '(\\b)alrm(\\b)': '\\1alarm\\2',
 '(\\b)alt(\\b)': '\\1alternate\\2',
 '(\\b)corr(\\b)': '\\1corrosion\\2',
 '(\\b)cr(\\b)': '\\1chemical resistant\\2'}

In [111]: data['text'] = data['text'].replace(d2, regex=True)

In [112]: data
Out[112]:
   id                                             text
0   1  accelerator action corrosion chemical resistant
1   2                         plate corrosion affinity
2   3                                  alarm alternate

where d - is a replacement dictionary.

PS don't use reserved words like (dict, list, etc) for variable names - it will shadow internal Python types, so you won;t be able to use them properly:

In [1]: dict = dict(a='aaa', b='bbb')

In [2]: dict
Out[2]: {'a': 'aaa', 'b': 'bbb'}

In [3]: dict2 = dict(c='ccc')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-650e1aa39edb> in <module>()
----> 1 dict2 = dict(c='ccc')

TypeError: 'dict' object is not callable

RegEx explanation:

'(\\b)word(\\b)' - means search for a word, preceeding and followed by a word boundary and put both word boundaries in capturing groups: first patenthesis - 1st capturing group, etc.

\\1 - in the substitution part says put there the contents of the first cpaturing group (word boundary in our case)