python - 滚动最大值不包括 Pandas 1.0 中的当前观察值

标签 python pandas rolling-average

使用 Pandas 1.0,我需要生成一个滚动最大值,其中包含前 3 个观察值的窗口,不包括当前观察值。在 R 中,这是通过

library(tidyverse)

test_df = data.frame(a = 1:5, b = c(40, 37, 60, 45, 40))
​
test_df <- test_df %>% mutate(
    rolling_max=rollapply(b, width = list(-1:-3), max, na.rm = TRUE, partial = 0, align = "right")
)
> test_df
  a  b rolling_max
1 1 40        -Inf
2 2 37          40
3 3 60          40
4 4 45          60
5 5 40          60

在 Python 中,pandas.rolling.apply() 函数似乎没有办法排除当前观察,因此这会产生意想不到的结果:

import pandas as pd
test_df = pd.DataFrame({'a': [1,2,3,4,5], 'b': [40,37,60,45,40]})
test_df['rolling_max'] = test_df['b'].rolling(3).apply(max)
test_df
   a   b  rolling_max
0  1  40          NaN
1  2  37          NaN
2  3  60         60.0
3  4  45         60.0
4  5  40         60.0

这输出了预期的结果,但它看起来像是一个笨拙且不可扩展的解决方案:

test_df['rolling_max'] = np.fmax(
    test_df['b'].shift(periods=1).to_numpy(), 
    test_df['b'].shift(periods=2).to_numpy(), 
    test_df['b'].shift(periods=3).to_numpy()
)
test_df
   a   b  rolling_max
0  1  40          NaN
1  2  37         40.0
2  3  60         40.0
3  4  45         60.0
4  5  40         60.0

有人可以推荐更好的方法吗?

最佳答案

这似乎可以满足您的需求:

test_df.rolling(2, min_periods=1).max()

关于python - 滚动最大值不包括 Pandas 1.0 中的当前观察值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61649484/

相关文章:

python - Pandas : to_csv() got an unexpected keyword argument

python - 计算 Pandas 数据框中多列中具有相同字符串值的总行数

pandas - 相对于 pandas 中其他 2 列的组,日期列上 4 天的滚动平均值

python - pandas 滚动窗口意味着 future

python - Django Rest Framework - 将带有文件和其他数据的多部分/表单数据发送到 API

python - 为什么 Python 生成器函数在语法上与 'regular' 函数没有不同的表示法?

python - 在numba中编译abs()比普通的python函数慢

python - 如何使用 Anaconda Python 3.6 在 64 位 Ubuntu 14.04 中安装 pygame

python - 根据多种条件在具有不同输出的 Pandas 中添加两列

python - 1 年滚动平均 Pandas 列日期