'How can I convert boolean values from np.diff() to the actual values
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.
- How can I get the exact values of each
False
orTrue
item in a separate array? - How can I get the location of each
False
orTrue
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.
Solution 1:[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].
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | AJH |