gpt4 book ai didi

python - Pandas fillna 和滚动平均值

转载 作者:行者123 更新时间:2023-12-04 08:35:15 24 4
gpt4 key购买 nike

我试图填充所有缺失值,直到数据帧结束,但无法这样做。在下面的示例中,我取了最后三个值的平均值。我的代码只填充到 2017-01-10,而我想填充到 2017-01-14。对于 1/14,我想使用 11,12 和 13 的值。请帮忙。

import pandas as pd

df = pd.DataFrame([
{"ds":"2017-01-01","y":3},
{"ds":"2017-01-02","y":4},
{"ds":"2017-01-03","y":6},
{"ds":"2017-01-04","y":2},
{"ds":"2017-01-05","y":7},
{"ds":"2017-01-06","y":9},
{"ds":"2017-01-07","y":8},
{"ds":"2017-01-08","y":2},
{"ds":"2017-01-09"},
{"ds":"2017-01-10"},
{"ds":"2017-01-11"},
{"ds":"2017-01-12"},
{"ds":"2017-01-13"},
{"ds":"2017-01-14"}
])

df["y"].fillna(df["y"].rolling(3,min_periods=1).mean(),axis=0,inplace=True)

结果:

           ds    y
0 2017-01-01 3.0
1 2017-01-02 4.0
2 2017-01-03 6.0
3 2017-01-04 2.0
4 2017-01-05 7.0
5 2017-01-06 9.0
6 2017-01-07 8.0
7 2017-01-08 2.0
8 2017-01-09 5.0
9 2017-01-10 2.0
10 2017-01-11 NaN
11 2017-01-12 NaN
12 2017-01-13 NaN
13 2017-01-14 NaN

期望的输出:

Desired output:

最佳答案

您可以遍历 y 中的值,如果遇到 nan 值,请查看前 3 个值并使用 .at[] 将前 3 个值的平均值设置为新值:

for index, value in df['y'].items():
if np.isnan(value):
df['y'].at[index] = df['y'].iloc[index-3: index].mean()

缺失值的结果数据框:

7   2017-01-08  2.000000
8 2017-01-09 6.333333
9 2017-01-10 5.444444
10 2017-01-11 4.592593
11 2017-01-12 5.456790
12 2017-01-13 5.164609
13 2017-01-14 5.071331

关于python - Pandas fillna 和滚动平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64831334/

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