Skip to main content
 首页 » 编程设计

python之以相反的顺序应用 Python Pandas 指数加权平均

2024年12月31日8kenshinobiy

以 pandas.DataFrame 为例:

In: cols = ['cols1', 'cols2'] 
In: df = pd.DataFrame({'col1': [1, 2, 3, 4], 'col2': [3, 4, 5, 6]}) 
 
Out:       col1  col2 
      0     1     3 
      1     2     4 
      2     3     5 
      3     4     6 

我正在使用指数加权平均值:

In: for i in range(len(df.columns)): 
       df[cols[i]] = df[cols[i]].ewm(com=None, span=None, halflife=None,  
                                     alpha=.8, min_periods=0, adjust=True, 
                                     ignore_na=False, axis=0).mean() 

效果很好!然而,权重是从上到下按指数递减的值应用的:

  Out:      col1      col2 
      0  1.000000  3.000000 
      1  1.833333  3.833333 
      2  2.774194  4.774194 
      3  3.756410  5.756410 

我想知道是否有办法以相反的顺序(自下而上)应用权重。我想要的输出是:

Out:          col1          col2 
      0     0.9391025     2.8173075 
      1     1.8494627     3.6982925 
      2     2.7499995     4.5833325 
      3     4.000000      6.000000 

请您参考如下方法:

kel's solution 的变体.

注意

df[col].reindex(index=df.index[::-1])

实现类似的结果:

df[col].sort_index(ascending=False)

一个区别是 reindex 就地更改索引,而 sort_index 将 inplace 作为一个选项。因此,与 reindex 不同,sort_index 的一个优点是您不需要在最后将内容切换回去:

df[col] = df[col].sort_index(ascending=False).ewm(...).mean()

另请注意,使用 sort_index 的解决方案当然假定索引值以正确的方式排序。如果不是,我不确定采用滚动平均值是否会 具有物理意义。