Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading