-1

I have a numpy array of np.shape=(n,)

I am attempting to iterate through each value of the array and subtract the 2nd value from the 1st, then see if the difference is greater than 1.

So, array[1]-array[0] > 1 ?, then array[2]-array[1] > 1 ?.

I read that this is simple with np.diff(), which returns for me another array of boolean True/False values:

np.diff(array) > 1 gives [False False True False True], for example.

  1. How can I get the exact values of each False or True item in a separate array?
  2. How can I get the location of each False or True within the array?

I tried array[array>1] and variations of this but nothing has worked thus far.

EDIT: I used AJH's answer below, which worked for me.

nukenine
  • 195
  • 1
  • 4
  • 12
  • I think you can put your condition in `np.where` to get the array with the values back. you can also get the index of each true – Rabinzel Mar 30 '22 at 15:35
  • 1
    Start with `x = np.diff(array)`. Look at that yourself. `x>1` gives that boolean array. Then try things like `x[x>1]` and `np.nonzero(x)` – hpaulj Mar 30 '22 at 15:41

1 Answers1

1

Hopefully, this answers your question:

# Gets the difference between consecutive elements.
exact_diffs = np.diff(array, n=1)

# true_diffs = exact values in exact_diffs that are > 1.
# false_diffs = exact values in exact_diffs that are <= 1.
true_diffs = exact_diffs[exact_diffs > 1]
false_diffs = exact_diffs[exact_diffs <= 1]

# true_indices = indices of values in exact_diffs that are > 1.
# false_indices = indices of values in exact_diffs that are <= 1.
true_indices = np.where(exact_diffs > 1)[0]
false_indices = np.where(exact_diffs <= 1)[0]

# Note that true_indices gets the corresponding values in exact_diffs.
# To get the indices of values in array that are at least 1 more than preceding element, do:
true_indices += 1

# and then you can index those values in array with array[true_indices].
AJH
  • 799
  • 1
  • 3
  • 16