List Of Tuples (string, Float)with Nan How To Get The Min Value?
I have a list of List of Tuples (string, float) with float('nan'). How can i get the tuple with the smallest number? If I use min I always get the nan. [('GroundBasedMechWT', nan),
Solution 1:
You can use a custom key, that will return a very high value for NaN
:
min(list, key=lambda x: float('inf') if math.isnan(x[1]) else x[1])
Solution 2:
You could also try this:
min(filter(lambda t: not math.isnan(t[1]), l), key=itemgetter(1))
where itemgetter
refers to operator.itemgetter
.
Solution 3:
>>>nan=float('NaN')>>>x=[('GroundBasedMechWT', nan), ('GroundBasedCTL', nan), ('GroundBasedManualWT', nan), ('GroundBasedManualLog', nan), ('CableManualWTLog', 60.77), ('CableManualWT', 58.52), ('CableManualLog', 68.17), ('CableManualCTL', nan), ('HelicopterManualWT', 96.82), ('HelicopterManualCTL', nan)]>>>nan<1
False
>>>nan<1.0
False
>>>min(x)
('CableManualCTL', nan)
I don't think nan is considered smaller than regular floats. Probably min is comparing the strings alphabetically.
(Not a complete answer, but might help)
Solution 4:
nan=float('NaN')
x=[('GroundBasedMechWT', nan), ('GroundBasedCTL', nan), ('GroundBasedManualWT', nan), ('GroundBasedManualLog', nan), ('CableManualWTLog', 60.77), ('CableManualWT', 58.52), ('CableManualLog', 68.17), ('CableManualCTL', nan), ('HelicopterManualWT', 96.82), ('HelicopterManualCTL', nan)]
val=('foo', float('Inf')) #thanks for teaching me thatfor tup in x:
if tup[1]<val[1]:
val=tup
print val
Fails on the empty list, but otherwise solves the problem.
Post a Comment for "List Of Tuples (string, Float)with Nan How To Get The Min Value?"