Home > OS >  How to multiply pandas dataframe columns with dictionary value where dictionary key matches datafram
How to multiply pandas dataframe columns with dictionary value where dictionary key matches datafram

Time:12-15

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?

CodePudding user response:

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

CodePudding user response:

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
  • Related