Multiply Dataframe column with a Series

Viewed 43

I have DataFrame df =

      yyyymmdd                   Domain      Revenue
0     20210119                 Kurzy.cz   1.095453
1     20210119            agro-bazar.cz  25.641102
2     20210119             ahaonline.cz  45.217855
3     20210120                 Kurzy.cz   2.536259
4     20210120            agro-bazar.cz   1.282010

and I want to multiply column Revenue by Series of coeficients based on date (yyyymmdd)

coef = 
    yyyymmdd
    20210119    0.038140
    20210120    0.035556
    20210121    0.035793
    Name: CPMVS, dtype: float64

I tried variants of :

df['weighted'] = 1 / (df.groupby(by=['yyyymmdd', 'Domain'])['Revenue'] * coef)

but groupby return only groupbyObject, not Series nor DF. When I do

df.mul(coef, axis=1) 

it returns DF full of NANs.

What am I doing wrong?

1 Answers

You can use map to substitute the values in the column yyyymmdd by the values from the series coeff, then fill the NaN values (values which can't be substituted) with 1 and multiply it by the Revenue column:

df['Revenue'] = df['yyyymmdd'].map(coeff).fillna(1).mul(df['Revenue'])

   yyyymmdd         Domain   Revenue
0  20210119       Kurzy.cz  0.041781
1  20210119  agro-bazar.cz  0.977952
2  20210119   ahaonline.cz  1.724609
3  20210120       Kurzy.cz  0.090179
4  20210120  agro-bazar.cz  0.045583
Related