如何实现滚动均值忽略空值

Jor*_*šis 5 python pandas python-polars

我正在尝试计算 RSI 指标。为此,我需要滚动平均损益。

我想计算滚动平均值忽略空值。因此平均值将通过现有值的总和和计数来计算。

例子:

window_size = 5

df = DataFrame(price_change: { 1, 2, 3, -2, 4 })

df_gain = .select(
            pl.when(pl.col('price_change') > 0.0)
            .then(pl.col('price_change'))
            .otherwise(None)
            .alias('gain')
          )

# UNKOWN HOW TO GET WANTED RESULT:
rol_mean_gain = df_gain.select(
                  pl.col('gain').rolling_mean(window_size=window_size, ignore_null=True)
                )
Run Code Online (Sandbox Code Playgroud)

以便计算 rol_mean_gain:[1, 2, 3, skip, 4] / 4 (not 5)

我知道 Pandas 有.mean(skipna=True).apply(pandas.np.nanmean) 但据我所知 Polars 不提供这样的 API。

Way*_*shi 1

我认为跳过空值是隐含的,请参阅此方法的文档min_periods中的描述。

df_gain.select(pl.col('gain').rolling_mean(window_size=window_size, min_periods=1))
Run Code Online (Sandbox Code Playgroud)

给我一个专栏1.0, 1.5, 2.0, 2.0, 2.5。请注意最后两列如何正确跳过空值。