I have a 4x1 array that I want to search for the minimum non zero value and find its index. For example:
theta = array([0,1,2,3]).reshape(4,1)
It was suggested in a similar thread to use nonzero() or where(), but when I tried to use that in the way that was suggested, it creates a new array that doesn't have the same indices as the original:
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. I am only interested in the first minimum value if there are duplicates.
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)] .
The numpy argmin() function takes arr, axis, and out as parameters and returns the array. To find the index of a minimum element from the array, use the np. argmin() function.
In your case, it returns, When you do np.argmin (theta [np.nonzero (theta)]) on the previous output, it returns the index of the value 1 which is 0. i,j = np.where ( theta==np.min (theta [np.nonzero (theta)])) where i,j are the indices of the minimum non zero element of the original numpy array
numpy.nonzero(a) [source] ¶ Return the indices of the elements that are non-zero. Returns a tuple of arrays, one for each dimension of a, containing the indices of the non-zero elements in that dimension. The values in a are always tested and returned in row-major, C-style order.
Equivalent ndarray method. Counts the number of non-zero elements in the input array. While the nonzero values can be obtained with a [nonzero (a)], it is recommended to use x [x.astype (bool)] or x [x != 0] instead, which will correctly handle 0-d arrays. A common use for nonzero is to find the indices of an array, where a condition is True.
You can also specify an axis for which you wish to find the min along: import numpy.ma as ma mx = ma.masked_array (x, mask=x==0) mx.min () A simple way would be to use a list comprehension to exclude zeros. The title of the question does say "in a numpy array (or a tuple)".
np.nonzero(theta)
returns the index of the values that are non-zero. In your case, it returns,
[1,2,3]
Then, theta[np.nonzero(theta)] returns the values
[1,2,3]
When you do np.argmin(theta[np.nonzero(theta)])
on the previous output, it returns the index of the value 1
which is 0.
Hence, the correct approach would be:
i,j = np.where( theta==np.min(theta[np.nonzero(theta)]))
where i,j
are the indices of the minimum non zero element of the original numpy array
theta[i,j]
or theta[i]
gives the respective value at that index.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With