Last active
June 27, 2019 21:26
-
-
Save travis23/f5ce6dce969b603fa92a38f7b0d56d4a to your computer and use it in GitHub Desktop.
[Find Index of First Non-zero Occurrence] #numpy #nonzero
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
def find_index_of_first_nonzero_occurrence(array): | |
""" | |
Find the index of the first non-zero occurrence in a numpy array. | |
This is essentially a wrapper around np.flatnonzero(). If there are | |
no non-zero values None is returned. | |
array (numpy array): Should be 1d array and all elements should be numeric | |
""" | |
try: | |
first_occurance_index = np.flatnonzero(array)[0] | |
except IndexError as err: | |
if err.args[0] == 'index 0 is out of bounds for axis 0 with size 0': | |
# No non-zero values are present | |
first_occurance_index = None | |
else: | |
# Index error from other causes(?) are passed through | |
raise IndexError(err) | |
return first_occurance_index |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment