简体   繁体   English

如何使用先前的滚动平均值填充熊猫数据框中的后续空值?

[英]How to fill subsequent null values in pandas dataframe using previous rolling mean values?

I have a dataframe like below.我有一个如下所示的数据框。

df=pd.DataFrame({ 'month' : [1,2,3,4,5,6],
                  'temp'  : [50,60,40,np.nan,np.nan,np.nan]})

df

Output:输出:

  month temp
0   1   50.0
1   2   60.0
2   3   40.0
3   4   NaN
4   5   NaN
5   6   NaN

I want to fill missing value using rolling average of previous two values.我想使用前两个值的滚动平均值来填充缺失值。 Now, in case of index 4(or month 5), I want to use calculated rolling mean at index 3 and index 2 value.现在,在索引 4(或第 5 个月)的情况下,我想在索引 3 和索引 2 值处使用计算出的滚动平均值。 So,所以,

  • temp at index 3: 50 (~ avg(60,40))索引 3 处的温度:50 (~ avg(60,40))
  • temp at index 4: 45 (~ avg(40,50))索引 4 处的温度:45 (~ avg(40,50))

Expected output:预期输出:

  month temp
0   1   50.0
1   2   60.0
2   3   40.0
3   4   50.0
4   5   45.0
5   6   47.5

I checked the documentation but there does not seem a way to do that.我检查了文档,但似乎没有办法做到这一点。 Any work around?有什么解决办法吗? Thank you.谢谢你。

As mentioned by @NoobVB, a similar question was already solved in this post.正如@NoobVB 所提到的,在这篇文章中已经解决了一个类似的问题。 You just have to adjust the code according to your problem.您只需要根据您的问题调整代码即可。 An alternative way to solve this for an extended version of your example data frame is given below:下面给出了为示例数据框的扩展版本解决此问题的另一种方法:

import pandas as pd
import numpy as np

df=pd.DataFrame({'month': [1,2,3,4,5,6,7,8],
                'temp': [50,60,40,np.nan,np.nan,np.nan,20,np.nan]})

series = df["temp"]
for i in range(series.isna().sum()):
  shifted_series = series.rolling(2).mean().shift(periods=1)
  series = series.combine_first(shifted_series)

df['new_temp'] = series

df

--------------------------------------------
    month   temp    new_temp
0   1       50.0    50.00
1   2       60.0    60.00
2   3       40.0    40.00
3   4       NaN     50.00
4   5       NaN     45.00
5   6       NaN     47.50
6   7       20.0    20.00
7   8       NaN     33.75
--------------------------------------------

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM