remove entries with nan values in python dictionary

后端 未结 4 1469
[愿得一人]
[愿得一人] 2021-01-18 12:47

I have the foll. dictionary in python:

OrderedDict([(30, (\'A1\', 55.0)), (31, (\'A2\', 125.0)), (32, (\'A3\', 180.0)), (43, (\'A4\', nan))])
4条回答
  •  深忆病人
    2021-01-18 13:29

    user308827,

    The code in your question seems to confuse keys and values and ignore the fact that your values are tuples. Here's a one liner using std libs and a dict comprehension that works in python 2,3:

    from collections import OrderedDict
    import math
    
    od = OrderedDict([(30, ('A1', 55.0)), (31, ('A2', 125.0)), (32, ('A3', 180.0)), (43, ('A4', float('Nan')))])
    
    no_nans = OrderedDict({k:v for k, v in od.items() if not math.isnan(v[1])})
    # OrderedDict([(30, ('A1', 55.0)), (31, ('A2', 125.0)), (32, ('A3', 180.0))])
    

提交回复
热议问题