【问题标题】:How do I replace the values of a specific timeframe with a weighting of the same timeframe from previous years?如何用前几年相同时间范围的权重替换特定时间范围的值?
【发布时间】:2021-10-25 03:01:53
【问题描述】:

我有一个数据框,其中包含 4 年的数据,看起来像这样:

Year Week Value
2018 1 25
2018 2 28
2018 3 26
2019 1 24
2019 2 34
2019 3 30
2020 1 27
2020 2 33
2020 3 32
2021 1 39
2021 2 43
2021 3 41

我想要做的是将 2021 年的值替换为同一时间范围内前 3 年值的权重。因此,在此示例中,仅将 2021 年第 1 周到第 3 周的值(可能还有其他几周需要单独处理)替换为:45%*2020 + 30%*2019 + 25%*2018

这将为我们提供 2021 年的以下信息:

Year Week Value
2021 1 20.65
2021 2 32.05
2021 3 29.9

我们通过执行以下操作获得了 2021 年第 3 周的值: 0.4532 + 0.330 + 0.25*26 = 14.4 + 9 + 6.5 = 29.9

此外,如果我愿意,我希望能够跳过年份,例如,2021 年可以基于 2020 年、2019 年和 2016 年。

【问题讨论】:

    标签: python python-3.x pandas dataframe


    【解决方案1】:

    您可以创建自定义函数,因为听起来您需要可自定义的参数。没有特定的 pandas 方法可以做到这一点:

    def f(df=df, years=[], weeks=[], weights=[], current_year=2021):
        df = df[df['Week'].isin(weeks)]
        series_weights = df['Year'].map({year : weight for year, weight in zip(years, weights)})
        df['Value'] = df['Value'] * series_weights
        df = df.assign(Year=current_year).groupby(['Year', 'Week'], as_index=False)['Value'].sum()
        return df
    
    
    f(years=[2018,2019,2020], weeks=[1,2,3], weights=[0.25,0.3,0.45])
    
    Out[1]: 
       Year  Week  Value
    0  2021     1  25.60
    1  2021     2  32.05
    2  2021     3  29.90
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      相关资源
      最近更新 更多