gpt4 book ai didi

python - 如何像它的代码一样显示 pandas 滚动窗口?

转载 作者:行者123 更新时间:2023-12-05 04:57:56 28 4
gpt4 key购买 nike

是的,我在 this question 的问题中修改了我的 pandas 数据框示例:但是这次的问题不一样了

import pandas as pd
import numpy as np

d=({'A':['2020-01-01','2020-01-02','2020-01-03','2020-01-04','2020-01-05','2020-01-06','2020-01-07','2020-01-08','2020-01-09','2020-01-10'],
'B':[100,110,120,175,164,169,155,153,156,200]})
df=pd.DataFrame(d)

A B
0 2020-01-01 100
1 2020-01-02 110
2 2020-01-03 120
3 2020-01-04 175
4 2020-01-05 164
5 2020-01-06 169
6 2020-01-07 155
7 2020-01-08 153
8 2020-01-09 156
9 2020-01-10 200

我知道 pandas 滚动窗口代码是这样的(对于我的情况):df['sums']=df['B'].rolling(window=3, center=False).sum()

            A    B   sums
0 2020-01-01 100 NaN #Here's the question:
1 2020-01-02 110 NaN #Why the rolling windows NaN is just 2, but the rolling window code is 3
2 2020-01-03 120 330.0
3 2020-01-04 175 405.0
4 2020-01-05 164 459.0
5 2020-01-06 169 508.0
6 2020-01-07 155 488.0
7 2020-01-08 153 477.0
8 2020-01-09 156 464.0
9 2020-01-10 200 509.0
Name: sum, dtype: float64

我想把它变成这样:

0  2020-01-01  100    NaN # To display rolling window
1 2020-01-02 110 NaN # Like the code
2 2020-01-03 120 NaN # Not 2 but 3 NaNs
3 2020-01-04 175 330.0
4 2020-01-05 164 405.0
5 2020-01-06 169 459.0
6 2020-01-07 155 508.0
7 2020-01-08 153 488.0
8 2020-01-09 156 477.0
9 2020-01-10 200 464.0
10 2020-01-11 NaN 509.0

有办法吗?我尝试添加 NaN=np.nan 它变成这样:

1  2020-01-02  110    NaN
2 2020-01-03 120 NaN
3 2020-01-04 175 330.0
.
.
9 2020-01-10 200 464.0
10 2020-01-11 NaN 509.0
0 2020-01-01 100 NaN

有什么解决办法吗?

最佳答案

系列开头有两个 NaN,因为此时您没有足够的数据进行滚动(1 和 2 而不是 3)。从第 3 行开始。

如果您希望 3NaN 开头,请使用 shift 链接您的滚动代码:

df['sums']=df['A'].rolling(window=3, center=False).sum().shift()

输出:

     A   sums
0 100 NaN
1 110 NaN
2 120 NaN
3 175 330.0
4 164 405.0
5 169 459.0
6 155 508.0
7 153 488.0
8 156 477.0
9 200 464.0

关于python - 如何像它的代码一样显示 pandas 滚动窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64211250/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com