<br><br><div class="gmail_quote">On Wed, Oct 24, 2012 at 4:47 AM, Robert Kern <span dir="ltr"><<a href="mailto:robert.kern@gmail.com" target="_blank">robert.kern@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
<div class="im">How about this?</div>
<br>
<br>
def nancumsum(x):<br>
    nans = np.isnan(x)<br>
    x = np.array(x)<br>
    x[nans] = 0<br>
    reset_idx = np.zeros(len(x), dtype=int)<br>
    reset_idx[nans] = np.arange(len(x))[nans]<br>
    reset_idx = np.maximum.accumulate(reset_idx)<br>
    cumsum = np.cumsum(x)<br>
    cumsum = cumsum - cumsum[reset_idx]<br>
    return cumsum<br></blockquote><div><br></div><div>Thank you for putting in the time to look at this.</div><div>  </div><div>It doesn't work for the first group of numbers if x[0] is non-zero.  Could perhaps concatenate a np.nan at the beginning to force a reset and adjust the returned array to not include the dummy value...</div>
<div><br></div><div>def nancumsum(x):</div><div>    x = np.concatenate(([np.nan], x))</div><div>    nans = np.isnan(x)</div><div>    x = np.array(x)</div><div>    x[nans] = 0</div><div>    reset_idx = np.zeros(len(x), dtype=int)</div>
<div>    reset_idx[nans] = np.arange(len(x))[nans]</div><div>    reset_idx = np.maximum.accumulate(reset_idx)</div><div>    cumsum = np.cumsum(x)</div><div>    cumsum = cumsum - cumsum[reset_idx]</div><div>    return cumsum[1:]</div>
<div><br></div><div><div>>>> a</div><div>array([  4.,   1.,   2.,   0.,  18.,   5.,   6.,   0.,   8.,   9.], dtype=float32)</div></div><div><br></div><div>If no np.nan, then 'nancumsum' and 'np.cumsum' should be the same...</div>
<div><br></div><div><div>>>> np.cumsum(a)</div><div>array([  4.,   5.,   7.,   7.,  25.,  30.,  36.,  36.,  44.,  53.], dtype=float32)</div></div><div><br></div><div><div>>>> nancumsum(a)</div><div>array([  4.,   5.,   7.,   7.,  25.,  30.,  36.,  36.,  44.,  53.])</div>
</div><div><br></div><div>>>> a[3] = np.nan</div><div><br></div><div><div>>>> np.cumsum(a)</div><div>array([  4.,   5.,   7.,  nan,  nan,  nan,  nan,  nan,  nan,  nan], dtype=float32)</div></div><div><br>
</div><div><div>>>> nancumsum(a)</div><div>array([  4.,   5.,   7.,   0.,  18.,  23.,  29.,  29.,  37.,  46.])</div></div><div><br></div><div>Excellent!</div><div><br></div><div>Kindest regards,</div><div>Tim</div>
<div><br></div></div>