how do you vectorize an expensive loop in python?

Try:

rate = degradation_rate_PV_power_perc_per_hour / 100

mask = ~((df.index != replacement_duration_PV_year * hour_per_year)
         & (df.index != 0))

df['degradation_factor_PV_power_frac'] = (
    df.groupby(mask.cumsum())['degradation_factor_PV_power_frac']
      .apply(lambda x: x.shift().sub(rate).cumprod())
      .fillna(df['degradation_factor_PV_power_frac'])
)

Output:

>>> df
         time_datetime  degradation_factor_PV_power_frac
0  2022-01-01 00:00:00                          1.000000
1  2022-01-01 01:00:00                          0.999999
2  2022-01-01 02:00:00                          0.999999
3  2022-01-01 03:00:00                          0.999998
4  2022-01-01 04:00:00                          0.999998

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top