Python 发展

使用pandas时, 您可能想要向后打开窗口

Share this for your friends.

使用pandas时, 您可能想要向后打开窗口

Open rolling window backwards in pandas

使用pandas时,您可能想要向后打开窗口。
本文介绍了如何执行此操作。


什么是窗口功能?

使用窗口功能,我们可以获得列表的一部分。此外,我们还可以获得该部分的摘要或平均值。
有关窗口功能的更多信息,请参阅上一篇文章。





什么是窗口方向?

如果计算低于csv的移动平均线,则初始一些记录显示 "NaN" ,因为它们没有足够的窗口宽度。
窗口向前打开。因此2019/01/07的窗口函数结果是 (7 + 8 + 9 + 10)/ 4 = 8.5

rolling_forward.csv

日期,值
2019/01 / 10,10
2019/01 / 09,9
2019/01 / 08,8
2019/01 / 07,7
2019/01 / 06,6
2019/01 / 05,5
2019/01 / 04,4
2019/01 / 03,3
2019/01 / 02,2
2019/01 / 01,1


rolling_forward.py

import pandas as pd

# read CSV
df_csv = pd.read_csv("rolling_forward.csv", encoding='shift-jis')

# get average in latest 4 records
df_csv["MA"] = df_csv["value"].rolling(window=4).mean()
print(df_csv)


结果

日期值MA
0 2019/01/10 10 NaN
1 2019/01/09 9 NaN
2 2019/01/08 8 NaN
3 2019/01/07 7 8.5
4 2019/01/06 6 7.5
5 2019/01/05 5 6.5
6 2019/01/04 4 5.5
7 2019/01/03 3 4.5
8 2019/01/02 2 3.5
9 2019/01/01 1 2.5 

我们如何向后打开窗口以获得2019/01/07的结果 (7 + 6 + 5 + 4)/ 4 = 5.5


改变窗口的方向

即使在文档数据框架中,也没有任何内容向后打开窗口。如何从中心位置打开窗户。

我很长时间没有得到任何信息。
然后我在stackoverflow中找到了一篇文章。

Rolling backwards is the same as rolling forward and then shifting the result:
x.rolling(window=3).sum().shift(-2)
python - How to Reverse Rolling Sum? - Stack Overflow

它说"你可以通过滚动前进和转移获得相同的结果。"
我尝试过这个。

rolling_forward.py

# shift
df_csv["MA2"] = df_csv["value"].rolling(window=4).mean().shift(-3)
print(df_csv)


结果

日期值MA MA2
0 2019/01/10 10 NaN 8.5
1 2019/01/09 9 NaN 7.5
2 2019/01/08 8 NaN 6.5
3 2019/01/07 7 8.5 5.5
4 2019/01/06 6 7.5 4.5
5 2019/01/05 5 6.5 3.5
6 2019/01/04 4 5.5 2.5
7 2019/01/03 3 4.5 NaN
8 2019/01/02 2 3.5 NaN
9 2019/01/01 1 2.5 NaN 


哦,它和我的预期一模一样。


最后

  • 向后滚动 = 滚动向前 + 转移



Share this for your friends.

If you felt this article is useful, please share.

にほんブログ村 IT技術ブログへ

-Python, 发展
-,

© 2024 ITips