【问题标题】:How to get pandas to roll through entire series?如何让熊猫滚动整个系列?
【发布时间】:2023-01-19 23:02:43
【问题描述】:

熊猫滚动功能

window_size == step_size 时的最后一个元素

当我的窗口大小和步长均为 3 时,我似乎无法滚动示例 9 元素系列的最后三个元素。

以下是 pandas 的预期行为吗?

我想要的结果

如果是这样,我如何滚动 Series 以便:

pd.Series([1., 1., 1., 2., 2., 2., 3., 3., 3.]).rolling(window=3, step=3).mean()

评估为pd.Series([1., 2., 3.,])?

例子

    import pandas as pd

    def print_mean(x):
        print(x)
        return x.mean()

    df = pd.DataFrame({"A": [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]})

    df["left"] = (
        df["A"].rolling(window=3, step=3, closed="left").apply(print_mean, raw=False)
    )
    df["right"] = (
        df["A"].rolling(window=3, step=3, closed="right").apply(print_mean, raw=False)
    )
    df["both"] = (
        df["A"].rolling(window=3, step=3, closed="both").apply(print_mean, raw=False)
    )
    df["neither"] = (
        df["A"].rolling(window=3, step=3, closed="neither").apply(print_mean, raw=False)
    )

这评估为:

     A  left  right  both  neither
0  0.0   NaN    NaN   NaN      NaN
1  1.0   NaN    NaN   NaN      NaN
2  2.0   NaN    NaN   NaN      NaN
3  3.0   1.0    2.0   1.5      NaN
4  4.0   NaN    NaN   NaN      NaN
5  5.0   NaN    NaN   NaN      NaN
6  6.0   4.0    5.0   4.5      NaN
7  7.0   NaN    NaN   NaN      NaN
8  8.0   NaN    NaN   NaN      NaN

并打印:

0    0.0
1    1.0
2    2.0
dtype: float64
3    3.0
4    4.0
5    5.0
dtype: float64
1    1.0
2    2.0
3    3.0
dtype: float64
4    4.0
5    5.0
6    6.0
dtype: float64
0    0.0
1    1.0
2    2.0
3    3.0
dtype: float64
3    3.0
4    4.0
5    5.0
6    6.0
dtype: float64

【问题讨论】:

  • 您确定要在此处使用 step,它“在每个步骤结果中评估 [s] 窗口,相当于切片为 [::step]?”

标签: python pandas dataframe pandas-rolling


【解决方案1】:

您可以尝试使用 % 运算符每 3 行进行子集化:

df[df.index % 3 == 0]

这将输出:

【讨论】:

    猜你喜欢
    • 2021-01-08
    • 1970-01-01
    • 2014-01-30
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 2018-07-30
    • 2021-10-17
    • 2016-04-19
    相关资源
    最近更新 更多