2

I've got the following code:

def chunk_trades(A):
    last = A[0]
    new = []
    for x in A.iteritems():
        if np.abs((x[1]-last)/last) > 0.1:
            new.append(x[1])
            last = x[1]
        else:
            new.append(last)
    s = pd.Series(new, index=A.index)
    return s

Sometimes last can be zero. In this case, I'd like it to just carry on gracefully as if last was almost zero.

What's the cleanest way?

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
cjm2671
  • 18,348
  • 31
  • 102
  • 161
  • So if `last` is zero, you want the `if` block to execute, not the `else` block, right? – Tim Pietzcker Jun 28 '16 at 10:26
  • 1
    `if last == 0 or np.abs(...) > 0.1`? Alternatively do exactly what you described, define an `epsilon = 0.0000001` and then do `/ (last or epsilon)`. when `last == 0` it is considered false and `epsilon` will be used in its place. – Bakuriu Jun 28 '16 at 10:26
  • That's right, I want the if block to execute. – cjm2671 Jun 28 '16 at 10:27

3 Answers3

1

Just Replace your line by this:

if not last or np.abs((x[1]-last)/last) > 0.1:

This will not raise an exception since the left assertion is checked first.

YOBA
  • 2,759
  • 1
  • 14
  • 29
1

Not sure if you would really want to divide by "almost 0", since the result will be "almost infinity", but you can also do this:

if last == 0:
   last = sys.float_info.min

This is the minimum positive normalized float, i.e. the value closest to zero.

Source: https://docs.python.org/2/library/sys.html#sys.float_info

advance512
  • 1,327
  • 8
  • 20
0

If I anderstand correctly, when last == 0 youl'll get ZeroDivisionError, won't you? If yes, please consider following slightly modified version of your code:

def chunk_trades(A):
    last = A[0]
    new = []
    for x in A.iteritems():
        try:
            if np.abs((x[1]-last)/last) > 0.1:
                new.append(x[1])
                last = x[1]
            else:
                new.append(last)
        except ZeroDivisionError:
            eps = 1e-18 # arbitary infinitesmall number
            last = last + eps
            if np.abs((x[1]-last)/last) > 0.1:
                new.append(x[1])
                last = x[1]
            else:
                new.append(last)

    s = pd.Series(new, index=A.index)
    return s
Mikhail T.
  • 1,240
  • 12
  • 21