Skip to content

Instantly share code, notes, and snippets.

@travis23
Last active June 27, 2019 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save travis23/f5ce6dce969b603fa92a38f7b0d56d4a to your computer and use it in GitHub Desktop.
Save travis23/f5ce6dce969b603fa92a38f7b0d56d4a to your computer and use it in GitHub Desktop.
[Find Index of First Non-zero Occurrence] #numpy #nonzero
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