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

How to multiply pandas dataframe columns with dictionary value where dictionary key matches dataframe index

Is there a better way than iterating over columns to multiply column values by dictionary values where the dictionary key matches a specific dataframe column? Give a dataframe of:

import pandas as pd
    df = pd.DataFrame({
    'category': [1,2,3,4,5],
    'a': [5,4,3,3,4],
    'b': [3,2,4,3,10],
    'c': [3, 2, 1, 1, 1]
})

And a dictionary of:

lookup = {1:0, 2:4, 3:1, 4:6, 5:2}

I can multiply each column other than ‘category’ by the dictionary value where the key matches ‘category’ this way:

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

for t in df.columns[1:]:
    df[t] = df[t].mul(df['category'].map(lookup)).fillna(df[t])

But there must be a more succinct way to do this other than iterating over columns?

>Solution :

import pandas as pd
df = pd.DataFrame({
    'category': [1,2,3,4,5],
    'a': [5,4,3,3,4],
    'b': [3,2,4,3,10],
    'c': [3, 2, 1, 1, 1]
})

lookup = {1:0, 2:4, 3:1, 4:6, 5:2}

out = df.set_index("category").mul(lookup, axis=0).reset_index()
print(out)

Output:

   category   a   b  c
0         1   0   0  0
1         2  16   8  8
2         3   3   4  1
3         4  18  18  6
4         5   8  20  2
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