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

Question:

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:

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?

Asked By: mweber

||

Answers:

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
Answered By: Chrysophylaxs

Another way

df.iloc[:,1:] =df.iloc[:,1:].mul(pd.Series(df['category'].map(lookup)), axis=0)

    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
Answered By: wwnde
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.