Home > database >  numpy: minimal absolute value above threshold
numpy: minimal absolute value above threshold

Time:11-14

From a multidimensional matrix I like to have the smallest absolute value above a tolerance value.

import numpy as np
np.random.seed(0)
matrix = np.random.randn(5,1,10)
tolerance = 0.1
np.amin(np.abs(matrix), axis=-1)
# array([[0.10321885],
#        [0.12167502],
#        [0.04575852],  # <- should not appear, as below tolerance
#        [0.15494743],
#        [0.21274028]])

Above code returns the absolute minimum over the last dimension. But I'd like to ignore small values (near 0) from determining the minimum. So in my example with tolerance = 0.1 the third row should contain the second smallest value.

With matrix[np.abs(matrix) >= tolerance] I can select values above tolerance but this flattens the array and therefore np.amin(...) cannot determine the minimum for the last dimension any more.

CodePudding user response:

You can replace the values smaller than 0.1 by for example 1, using np.where:

np.where(np.abs(matrix)< 0.1,1,np.abs(matrix))

Then apply np.amin on top :

np.amin(np.where(np.abs(matrix)< 0.1,1,np.abs(matrix)),axis=-1)

Result:

array([[0.10321885],
       [0.12167502],
       [0.18718385],
       [0.15494743],
       [0.21274028]])
  • Related