1

I checked this answer but it only applies to entire columns.

I have a dataframe with 3 columns (name, date, value)

     Name         Dt    Value
0    aaaa 2018-01-01      100
1    bbbb 2018-07-02      200
2    aaaa 2019-01-01      300
3    aaaa 2020-01-04      500

I also have a dictionary of yearly scale factors. what i want to do is to multiply all value in a year by the corresponding scale factor.

I tried doing something like this

df[df['Name'] == a & df['Dt'].dt.year == i]['Value'] *= dictionary[i]

this doesn't seem to be working. is there a way to do this without looping through every row?

Community
  • 1
  • 1
Hkk
  • 111
  • 1
  • 9

1 Answers1

3

Use loc and map

d = {2018: 100, 2019: 1000, 2020: 10000}

df.loc[
    (df.Name == 'aaaa') & (df.Dt.dt.year == 2018), 'Value'
] *= df.Dt.dt.year.map(d)

print(df)

   Name         Dt    Value
0  aaaa 2018-01-01  10000.0
1  bbbb 2018-07-02    200.0
2  aaaa 2019-01-01    300.0
3  aaaa 2020-01-04    500.0
piRSquared
  • 285,575
  • 57
  • 475
  • 624