You can use applymap:

df = pd.DataFrame({'nearby_subway_station':['yes','no'], 'Station':['no','yes']})
print (df)
  Station nearby_subway_station
0      no                   yes
1     yes                    no

dict_map_yn_bool={'yes':True, 'no':False}

df = df.applymap(dict_map_yn_bool.get)
print (df)
  Station nearby_subway_station
0   False                  True
1    True                 False

Another solution:

for x in df:
    df[x] = df[x].map(dict_map_yn_bool)
print (df)
  Station nearby_subway_station
0   False                  True
1    True                 False

Thanks Jon Clements for very nice idea - using replace:

df = df.replace({'yes': True, 'no': False})
print (df)
  Station nearby_subway_station
0   False                  True
1    True                 False

Some differences if data are no in dict:

df = pd.DataFrame({'nearby_subway_station':['yes','no','a'], 'Station':['no','yes','no']})
print (df)
  Station nearby_subway_station
0      no                   yes
1     yes                    no
2      no                     a

applymap create None for boolean, strings, for numeric NaN.

df = df.applymap(dict_map_yn_bool.get)
print (df)
  Station nearby_subway_station
0   False                  True
1    True                 False
2   False                  None

map create NaN:

for x in df:
    df[x] = df[x].map(dict_map_yn_bool)

print (df)
  Station nearby_subway_station
0   False                  True
1    True                 False
2   False                   NaN

replace dont create NaN or None, but original data are untouched:

df = df.replace(dict_map_yn_bool)
print (df)
  Station nearby_subway_station
0   False                  True
1    True                 False
2   False                     a
Answer from jezrael on Stack Overflow
Top answer
1 of 3
15

You can use applymap:

df = pd.DataFrame({'nearby_subway_station':['yes','no'], 'Station':['no','yes']})
print (df)
  Station nearby_subway_station
0      no                   yes
1     yes                    no

dict_map_yn_bool={'yes':True, 'no':False}

df = df.applymap(dict_map_yn_bool.get)
print (df)
  Station nearby_subway_station
0   False                  True
1    True                 False

Another solution:

for x in df:
    df[x] = df[x].map(dict_map_yn_bool)
print (df)
  Station nearby_subway_station
0   False                  True
1    True                 False

Thanks Jon Clements for very nice idea - using replace:

df = df.replace({'yes': True, 'no': False})
print (df)
  Station nearby_subway_station
0   False                  True
1    True                 False

Some differences if data are no in dict:

df = pd.DataFrame({'nearby_subway_station':['yes','no','a'], 'Station':['no','yes','no']})
print (df)
  Station nearby_subway_station
0      no                   yes
1     yes                    no
2      no                     a

applymap create None for boolean, strings, for numeric NaN.

df = df.applymap(dict_map_yn_bool.get)
print (df)
  Station nearby_subway_station
0   False                  True
1    True                 False
2   False                  None

map create NaN:

for x in df:
    df[x] = df[x].map(dict_map_yn_bool)

print (df)
  Station nearby_subway_station
0   False                  True
1    True                 False
2   False                   NaN

replace dont create NaN or None, but original data are untouched:

df = df.replace(dict_map_yn_bool)
print (df)
  Station nearby_subway_station
0   False                  True
1    True                 False
2   False                     a
2 of 3
10

You could use a stack/unstack idiom

df.stack().map(dict_map_yn_bool).unstack()

Using @jezrael's setup

df = pd.DataFrame({'nearby_subway_station':['yes','no'], 'Station':['no','yes']})
dict_map_yn_bool={'yes':True, 'no':False}

Then

df.stack().map(dict_map_yn_bool).unstack()

  Station nearby_subway_station
0   False                  True
1    True                 False

timing
small data

bigger data

🌐
Reddit
reddit.com › r/learnpython › how do i map the keys of a dictionary to the columns of a pandas dataframe?
r/learnpython on Reddit: How do I map the keys of a dictionary to the columns of a pandas dataframe?
January 12, 2020 -

Hi y'all,

i have a list of dictionaries (multidict), which holds a lot of different values. I also have an empty dataframe with set columns which do not coincide with keys of the dictionaries.

I need to append each dictionary to the DataFrame and map each key of the dictionary to the right (and fixed) column. How do i pass the values for each dictionary to the right column and row?

Here is my code so far with exemplary data:

multidict = [{'website': 'http://www.example.de/', 'time': '2020-01-05 17:33:53.973205', 'norating': 112, 'name': 'Name', 'rating': 4.4, 'phone': '123456789', 'adress': 'adress', 'typus': "['restaurant', 'bowling_alley', 'lodging', 'food', 'point_of_interest', 'establishment']"},{'website': 'http://www.exmpl.de/', 'time': '2020-02-05 17:33:53.973205', 'norating': 12, 'name': 'Name2', 'rating': 4.3, 'phone': '987654321', 'adress': 'address', 'typus': "['whatever', 'point_of_interest', 'establishment']"}]

df = pd.DataFrame()
df.columns = ['timestamp', 'name', 'adress', 'phone', 'website', 'rating', 'number_of_ratings', 'type']

for i in multidict:
    #How do I remap the keys of the dictionary here to the columns of the dataframe???
Discussions

python - Pandas: map column using a dictionary on multiple columns - Stack Overflow
I have a dataframe with None values in one column. I would like to replace this None values with the maximum value of the "category" for the same combination of other columns. Example: pa... More on stackoverflow.com
🌐 stackoverflow.com
python - How to map to multiple values in a dictionary in pandas - Stack Overflow
In [2696]: df = pd.concat([df,pd.DataFrame(df.Name.map(d).tolist(), columns=['Gender', 'Age'])], axis=1) In [2695]: df Out[2696]: Name Gender Age 0 Jack Male 22 1 Alex Male 26 2 Jackie Female 28 3 Susan Female 30 ... d = {'Alex':['Male','26'],'Jackie':['Female','28'],'Susan':['Female','30']} print (df) Name Gender Age 0 Alex Male 26 1 Jack NaN NaN 2 Jackie Female 28 3 Susan Female 30 · Use DataFrame.from_dict from your dictionary ... More on stackoverflow.com
🌐 stackoverflow.com
pandas - Mapping Python dictionary with multiple keys into dataframe with multiple columns matching keys - Stack Overflow
I have a dictionary that I would like to map onto a current dataframe and create a new column. I have keys in a tuple, which map onto two different columns in my dataframe. dct = {('County', 'State... More on stackoverflow.com
🌐 stackoverflow.com
June 1, 2018
python - Fastest way to map a dict on a df (multiple columns) - Stack Overflow
This is of course only a sample of my df, and I have multiple dicts like this one. I am looking for the fastest way to map this dict to this dataframe, based on the 3 columns. More on stackoverflow.com
🌐 stackoverflow.com
January 13, 2022
🌐
DataScientYst
datascientyst.com › pandas-map-column-dictionary
How to Map Column with Dictionary in Pandas
March 29, 2025 - Finally we can use pd.Series() of Pandas to map dict to new column. The difference is that we are going to use the index as keys for the dict: ... To use a given column as a mapping we can use it as an index.
🌐
YouTube
youtube.com › luke chaffey
map multiple columns by a single dictionary in pandas - YouTube
python: map multiple columns by a single dictionary in pandasThanks for taking the time to learn more. In this video I'll go through your question, provide v...
Published: July 18, 2024
Views: 13
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › pandas › using-dictionary-to-remap-values-in-pandas-dataframe-columns
Using dictionary to remap values in Pandas DataFrame columns - GeeksforGeeks
July 11, 2025 - The replace() function in Pandas allows us to remap values using a dictionary. It works directly on a DataFrame column and modifies the values based on the provided mapping.
🌐
IncludeHelp
includehelp.com › python › how-to-map-a-function-using-multiple-columns-in-pandas.aspx
Python - How to map a function using multiple columns in pandas?
# Importing pandas package import pandas as pd # Importing numpy package import numpy as np # Creating a dictionary d = { 'a':[1,2,3,4,5], 'b':[6,7,8,9,10], 'c':[11,12,13,14,15] } # Creating a DataFrame df = pd.DataFrame(d) # Display Original df print("Original DataFrame:\n",df,"\n") # Defining a function def fun(a,b): return a*b # Calling this function which takes # values from multiple columns df['d'] = df.apply(lambda x: fun(a = x['a'], b = x['b']), axis=1) # Display result print("Result:\n",df)
🌐
Finxter
blog.finxter.com › home › learn python blog › a visual guide to pandas map( ) function
A Visual Guide to Pandas map( ) function - Be on the Right Side of Change
November 29, 2023 - In Machine Learning, there are routines to convert a categorical variable column to multiple discrete numerical columns. Such a process of encoding is termed as One-Hot Encoding in Machine Learning terminology. We have discussed Pandas apply function in detail in another tutorial. The map and apply functions have some major differences between them. They are; ... apply is used for applying functions that are not available as vectorized aggregation routines on DataFrames · A map function is used majorly to map values of a Series using a dictionary.
🌐
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.
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.Series.map.html
pandas.Series.map — pandas 3.0.6 documentation
Apply a function row-/column-wise. ... Apply a function elementwise on a whole DataFrame. ... When arg is a dictionary, values in Series that are not in the dictionary (as keys) are converted to NaN. However, if the dictionary is a dict subclass that defines __missing__ (i.e. provides a method for default values), then this default is used rather than NaN. ... map accepts a dict or a Series.
🌐
datagy
datagy.io › home › pandas tutorials › pandas dataframes › transforming pandas columns with map and apply
Transforming Pandas Columns with map and apply • datagy
March 20, 2023 - Pandas provides a wide array of solutions to modify your DataFrame columns · Vectorized, built-in functions allow you to apply functions in parallel, applying them to multiple records at the same time · The Pandas .map() method can pass in a dictionary to map values to a dictionaries keys
🌐
Kanoki
kanoki.org › 2019 › 04 › 06 › pandas-map-dictionary-values-with-dataframe-columns
Pandas Map Dictionary values with Dataframe Columns | kanoki
April 6, 2019 - So we have created a new column called Capital which has the National capital of those five countries using the matching dictionary value ... Let’s multiply the Population of this dataframe by 100 and store this value in a new column called as inc_Population · df['inc_Population']=df.Population.map(lambda x: x*100)
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.