Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Get minimum value without -inf

I am trying to find the minimum of an array without -inf values. What I could find there is numpy function to filter out NaNs but not -inf:

import numpy as np
np.nanmin([1, 2, np.nan, np.NINF])

The desired output is:

1
like image 379
brium-brium Avatar asked Dec 11 '16 17:12

brium-brium


3 Answers

Select the non -Infs and get the min ignoring NaNs with np.nanmin -

np.nanmin(a[a != -np.inf])

Sample run -

In [209]: a
Out[209]: array([  1.,   2.,  nan, -inf])

In [210]: np.nanmin(a[a != -np.inf])
Out[210]: 1.0
like image 189
Divakar Avatar answered Sep 18 '22 13:09

Divakar


Use np.isfinite to get only real values:

import numpy as np
a = np.array([1, 2, np.nan, np.NINF])
min_value = a[np.isfinite(a)].min()
# >>> 1.0
like image 20
Daniel Avatar answered Sep 21 '22 13:09

Daniel


An alternative approach using masked arrays:

>>> import numpy as np
>>> np.ma.masked_invalid([1, 2, np.nan, np.NINF]).min()
1.0

masked_invalid will ignore Inf and NaN values.

like image 27
Imanol Luengo Avatar answered Sep 19 '22 13:09

Imanol Luengo