Pandas - multiply column values by dictionary values

Viewed 12

I have a dataframe of football stats with scaled values, like so:

team match Gls  Ast  SoT Sha Crs Fls
Arg  987.  0.11 0.04 0.8 0.5 0.2 0.65
....

Now I would like to apply weights to each value, according to the following dictionary:

weights = {
    'Gls':8,
    'Ass':5,
    'SoT':1.5,
    'Sha':1.3,
    'Crs':1.2,
    'Fld':1.2
}

Each dict value is scalar to be multiplied by its correpondent column value.

How do I approach this using apply() in pandas?

1 Answers

I have an approach with melt:

weights = {
    'Gls':8,
    'Ass':5,
    'SoT':1.5,
    'Sha':1.3,
    'Crs':1.2,
    'Fld':1.2
}

(df
 .melt(id_vars=['team', 'match'])
 .assign(new=lambda x: x.value * x.variable.map(weights))
)

or with set_index:


(df
 .set_index(['team', 'match'])
 .mul(weights)
 .reset_index()
)
Related