NumPy | nanargmin method
nanargmin(~) method ignores all missing values (i.e.
NaNs) returns the index that corresponds to the smallest element in the array.
The input array.
The axis along which to compute the method. For 2D arrays, if
axis=0, then the method is performed column-wise, and if
axis=1 then row-wise. If no axis is provided, then Numpy will deem your array as a flattened array.
axis is provided, then a scalar is returned. Otherwise, a Numpy array is returned.
x = np.array([5,np.NaN,1,3])np.nanargmin(x)2
Here, 2 is returned because the smallest value (i.e. 1) is located at index 2. In contrast, the
np.argmin(x) method would return 1 since it considers
NaN to be the smallest.
Suppose we have the following 2D Numpy array:
x = np.array([[5,np.NaN],[1,3]])xarray([[ 5., nan],[ 1., 3.]])
Min index of entire array
To obtain the index of the minimum value in the entire array, leave out the
Min indices of every column
To obtain the index of the minimum values column-wise, set
np.nanargmin(x, axis=0)array([1, 1])
Here, we're going over each column of the matrix and computing the index of its smallest value, while ignoring any missing values.
Min indices of every row
To obtain the index of the minimum values row-wise, set
np.nanargmin(x, axis=1)array([0, 0])
Here, we're going over each row of the matrix and computing the index of its smallest value, while ignoring any missing values.