Aaron England
Aaron England

Reputation: 1273

Map multiple columns simultaneously with different maps

I have a pandas data frame here:

import pandas as pd

df = pd.DataFrame({'col1': ['a','a','b','b'],
                   'col2': ['a','a','b','b']})

I have a mapping dictionary here:

dict_map = {'col1': {'a': 0.5, 'b': 1.0},
            'col2': {'a': 0.6, 'b': 0.9}}

I want to map each column with the corresponding dictionary so that the data frame will look like:

    col1  col2
0   0.5   0.6
1   0.5   0.6
2   1.0   0.9
3   1.0   0.9

I can easily iterate through the columns in df and achieve the desired result, but I am trying to avoid iterating. How can I do this without iterating?

Upvotes: 2

Views: 582

Answers (2)

Yashar Ahmadov
Yashar Ahmadov

Reputation: 1636

I would use the df.replace(dict) function to avoid loops.

Upvotes: 4

user17242583
user17242583

Reputation:

You can use pandas.DataFrame.replace:

df = df.replace(dict_map)

Output:

>>> df
   col1  col2
0   0.5   0.6
1   0.5   0.6
2   1.0   0.9
3   1.0   0.9

Upvotes: 5

Related Questions