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?

3
  • So if last is zero, you want the if block to execute, not the else block, right? Commented Jun 28, 2016 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. Commented Jun 28, 2016 at 10:26
  • That's right, I want the if block to execute. Commented Jun 28, 2016 at 10:27

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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 

1 Comment

you could use any infinitesmall number instead 1e-18

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.