'Take only elements from array that satisfy condition from its diff in Python
I am trying to write a function that takes as input an array, compute the diff of the array, and take only the values from the array where the index matches the index of diff(array) meeting a certain condition (diff values in the range [low_thresh, high_thresh]).
Here the code that I wrote in Python using numpy:
def get_rid_jumps(trace, low_tresh, high_thresh):
trace_diff = np.pad(np.diff(trace), 1)
trace_diff = trace_diff[1:]
trace_out_jumps = trace[trace_diff < high_thresh and trace_diff > low_tresh]
return trace_out_jumps
But I do receive the error "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()". Please let me know if you have any suggestions.
Solution 1:[1]
The and doesn't do an element-wise comparison. For that, you need https://numpy.org/doc/stable/reference/generated/numpy.logical_and.html
trace_out_jumps = trace[np.logical_and(trace_diff < high_thresh, trace_diff > low_tresh)]
But for this to work, you'll also need to convert trace to an array (as compared to the list you gave in your comments)
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 |
