## Python - Finding indices of the first non-zero element to the left for each element

numpy set all non zero values to 1
python find first non zero element
numpy find first non-zero
numpy check if any element is zero
numpy get true indices
numpy nonzero
numpy condition nonzero

I know there are lots of similar questions, but this one is sightly different.

Given any row such as `row = [1 0 0 1 0 1 0 1]` I want to output a row that says `output = [0 -1 -1 0 -1 3 -1 5]`

and basically this is saying, the first 1, points to itself. The 2nd `1`, which has index 3, points to the `1` to its left and since that `1` has an index 0, it is 0. The 3rd `1` points to the `1` to it's left, which has index 3. And lastly, the 4th `1` points to the first one to it's left which has index `5`. Lastly, all the `0`s are set to -1.

I am able to get the indices of the where all the `1` are using `numpy.nonzero(row)` but I'm not sure how to space out these indices in the same dimensions as input array.

It's rather easy if you iterate on the list (using `enumerate` to keep track of the element index too) and store the last index where 1 (below any non-zero value) was seen (except for the first time)

```row = [1, 0, 0, 1, 0, 1, 0, 1]

prev_index = None

result = []
for i,v in enumerate(row):
if v:
result.append(i if prev_index is None else prev_index)
prev_index = i
else:
result.append(-1)

>>> result
[0, -1, -1, 0, -1, 3, -1, 5]
```

This is difficult to achieve with a list comprehension because of the need to store the previous index.

Python find first instance of non zero number in list, Python 2: Basically, it uses next() to find the first value, or return None if there isn't one. enumerate() is used to make an iterator that iterates over index,value The indices of the nonzero elements are myDict[element] . numpy.nonzero () in Python numpy.nonzero () function is used to Compute the indices of the elements that are non-zero. It returns a tuple of arrays, one for each dimension of arr, containing the indices of the non-zero elements in that dimension. The corresponding non-zero values in the array can be obtained with arr [nonzero (arr)].

Basically what we want is to replace all `0`s with `-1`, and all non-zeros with the index of the previous zero, if I understood it correctly.

We can thus create an array of `-1`s with the same length as the given array, and then replace a view of zeros with the result of `np.where`:

```outp = np.full(a.shape, -1)
idxs = a.nonzero()
if len(idxs) > 0:
outp[idxs] = np.concatenate(([0], idxs[0][:-1]))
```

For example:

```>>> a = np.array([1, 0, 0, 1, 0, 1, 0, 1])
>>> outp = np.full(a.shape, -1)
>>> idxs = a.nonzero()
>>> outp[idxs] = np.concatenate(([0], idxs[0][:-1]))
>>> outp
array([ 0, -1, -1,  0, -1,  3, -1,  5])
```

If the first value is a zero however, it will still have value `-1`, and thus have an index out of range, but it is not clear, at least to me, what should happen in that case.

We can write it a bit more elegant as:

```outp = np.full(a.shape, -1)
idxs, = a.nonzero()
if len(idxs) > 0:
outp[idxs[1:]] = idxs[:-1]
outp[idxs[0]] = idxs[0]
```

This allows us to fill in a value before the first non-zero:

```outp = np.full(a.shape, -1)
idxs, = a.nonzero()
if len(idxs) > 0:
outp[idxs[1:]] = idxs[:-1]
outp[idxs[0]] = idxs[0]
outp[:idxs[0]] = 0  # or another value before the first non-zero
```

numpy.nonzero() in Python, nonzero() function is used to Compute the indices of the elements that are non-​zero. It returns a tuple of arrays, one for each dimension of arr, containing the  val = next((index for index,value in enumerate(myList) if value != 0), None) Basically, it uses next () to find the first value, or return None if there isn't one. enumerate () is used to make an iterator that iterates over index,value tuples so that we know the index that we're at.

Using list comprehension.

```row = [1, 0, 0, 1, 0, 1, 0, 1]
output = [idx-(idx!=0)-list(reversed(row[:max(idx, 1)])).index(1) if i else -1 for idx, i in enumerate(row)]
print(output) # -> [0, -1, -1, 0, -1, 3, -1, 5]
```

Python, Python | Replace elements in second list with index of same element in first list Python | Pandas Series.nonzero() to get Index of all non zero values in a series  Python’s list data type provides this method to find the first index of a given element in list or a sub list i.e. list.index(x[, start[, end]])

numpy.nonzero, Return the indices of the elements that are non-zero. Returns a tuple of The result of this is always a 2-D array, with a row for each non-zero element. A common use for nonzero is to find the indices of an array, where a condition is True. np.argmin(theta[np.nonzero(theta)]) gives an index of zero, which clearly isn't right. I think this is because it creates a new array of non zero elements first. The last sentence is correct => the first one is wrong since it is expected to give the index in the new array. Let's now extract the correct index in the old (original) array:

Find indices and values of nonzero elements, If X contains no nonzero elements or is empty, then find returns an empty k = find( X , n ) returns the first n indices corresponding to the nonzero elements in X . indexing numbers the elements in the columns from top to bottom, left to right. Usually, we require to find the index, in which the particular value is located. There are many method to achieve that, using index() etc. But sometimes require to find all the indices of a particular value in case it has multiple occurrences in list.

first nonzero element (Trac #1673) · Issue #2269 · numpy/numpy , to find the index of the first nonzero element of array A. Doesn't have to only be first nonzero, first any value would be useful. quick result, however a chunking approach written in python has proved to be suitably quick, and much more flexible to boot, for my case. I don't think that's worded quite right. Python | Index of Non-Zero elements in Python list Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming.