我需要对一列应用滚动均值,如图 1 s3 所示,在我应用滚动均值并设置窗口 = 5 后,我得到了正确答案,但前 4 行留空,如图 2 sa3 所示。
我想用 pic1 s3 中直到当前行的所有数据的平均值填充 pic2 sa3 中的前 4 个空单元格,如 pic3 a3 所示。
最佳答案
我认为 rolling
中需要参数 min_periods=1
:
min_periods : int, default None
Minimum number of observations in window required to have a value (otherwise result is NA). For a window that is specified by an offset, this will default to 1.
df = df.rolling(5, min_periods=1).mean()
示例:
np.random.seed(1256)
df = pd.DataFrame(np.random.randint(10, size=(10, 5)), columns=list('abcde'))
print (df)
a b c d e
0 1 5 8 8 9
1 3 6 3 0 6
2 7 0 1 5 1
3 6 6 5 0 4
4 4 9 4 6 1
5 7 7 5 8 3
6 0 7 2 8 2
7 4 8 3 5 5
8 8 2 0 9 2
9 4 7 1 5 1
df = df.rolling(5, min_periods=1).mean()
print (df)
a b c d e
0 1.000000 5.000000 8.00 8.000000 9.000000
1 2.000000 5.500000 5.50 4.000000 7.500000
2 3.666667 3.666667 4.00 4.333333 5.333333
3 4.250000 4.250000 4.25 3.250000 5.000000
4 4.200000 5.200000 4.20 3.800000 4.200000
5 5.400000 5.600000 3.60 3.800000 3.000000
6 4.800000 5.800000 3.40 5.400000 2.200000
7 4.200000 7.400000 3.80 5.400000 3.000000
8 4.600000 6.600000 2.80 7.200000 2.600000
9 4.600000 6.200000 2.20 7.000000 2.600000
关于python - 将滚动平均值应用于列时如何填充第一个 N/A 单元格-python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51043135/