title: How to use previous N values in pandas column to fill NaNs?
body: <p>Say I have a time series data as below.</p>
  
  <pre><code> df
         priceA    priceB
    0     25.67    30.56
    1     34.12    28.43
    2     37.14    29.08
    3     Nan       34.23
    4     32          Nan
    5     18.75    41.1
    6     Nan       45.12
    7     23          39.67
    8     Nan       36.45
    9      36         Nan
  </code></pre>
  
  <p>Now I want to fill NaNs in column <strong>priceA</strong> by taking mean of previous N values in the column. In this case take N=3.
  And for column <strong>priceB</strong> I have to fill Nan by value M rows above(current index-M).</p>
  
  <p>I tried to write for loop for it which is not a good practice as my data is too large. Is there a better way to do this?</p>
  
  <pre><code>N=3
  M=2
  def fillPriceA( df,indexval,n):
        temp=[ ]
        for i in range(n):
            if i &lt; 0:
                  continue
            temp.append(df.loc[indexval-(i+1), 'priceA'])
  
        return np.nanmean(np.array(temp, dtype=np.float))
  
  def fillPriceB(df,  indexval, m):
          return df.loc[indexval-m, 'priceB']
  
  for idx, rows for df.iterrows():
           if idx&lt; N: 
                 continue
           else:
                  if rows['priceA']==None:
                       rows['priceA']= fillPriceA(df, idx,N)
                  if rows['priceB']==None:
                       rows['priceB']=fillPrriceB(df,idx,M)
  </code></pre>
  
  <p>Expected output:</p>
  
  <pre><code>        priceA      priceB
  0      25.67        30.56
  1      34.12        28.43
  2      37.14        29.08
  3      32.31        34.23
  4      32             29.08
  5      18.75       41.1
  6       27.68      45.12
  7       23            39.67
  8       23.14      36.45
  9       36            39.67
  </code></pre>