remove entries with nan values in python dictionary

后端 未结 4 1478
[愿得一人]
[愿得一人] 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:15

    Your original code didn't actually have pandas and importing it just to filter for NaN seems excessive. However, your code was using numpy (np).

    Assuming your first line should read:

    dict_cg = OrderedDict([(30, ('A1', 55.0)), (31, ('A2', 125.0)), (32, ('A3', 180.0)), (43, ('A4', np.nan))])
    

    This line is close to what you had and works, although it requires you import the default library numbers:

    OrderedDict([(k, vs) for k, vs in d.items() if not any ([isinstance(v, numbers.Number) and np.isnan(v) for v in vs])])
    

    This way, you don't need pandas, your result is still an OrderedDict (as you had before) and you don't run into problems with the strings in the tuples, since conditions around and are evaluated left to right.

提交回复
热议问题