首页 > 解决方案 > 如何从列表中删除具有 NaN 值的字典

问题描述

这似乎是一件相当简单的事情,但我还没有在这里找到答案。

我有一个字典列表,列表中的一些字典具有 NaN 值。如果其中包含 NaN 值,我只需要从列表中删除任何字典。

我自己尝试了几种不同的方法。这是使用过滤器和 lambda 函数的一次尝试,它得到了 TypeError(“必须是实数,而不是 dict_values”,这是有道理的):

from math import isnan

def remove_dictionaries_missing_data(list_of_dictionaries):
    return list(filter(lambda dictionary: not math.isnan(dictionary.values()), \
                                          list_of_dictionaries))

我还尝试了几个嵌套循环和一些我真的不确定的代码并得到了同样的错误:

from math import isnan

def remove_dictionaries_missing_data(list_of_dictionaries):
    cleaned_list = []
    for dictionary in list_of_dictionaries:
        if not math.isnan(dictionary[value] for value in dictionary.values()):
            cleaned_list.append(dictionary)
    return cleaned_list

...最后只有一个列表理解(同样的错误):

from math import isnan
def remove_movies_missing_data(movies):
    return [movie for movie in movies if not math.isnan(movie.values())]

编辑:

这是我正在使用的列表示例:

[{'year': 2013,
  'imdb': 'tt2005374',
  'title': 'The Frozen Ground',
  'test': 'nowomen-disagree',
  'clean_test': 'nowomen',
  'binary': 'FAIL',
  'budget': 19200000,
  'domgross': nan,
  'intgross': nan,
  'code': '2013FAIL',
  'budget_2013$': 19200000,
  'domgross_2013$': nan,
  'intgross_2013$': nan,
  'period code': 1.0,
  'decade code': 1.0},
 {'year': 2011,
  'imdb': 'tt1422136',
  'title': 'A Lonely Place to Die',
  'test': 'ok',
  'clean_test': 'ok',
  'binary': 'PASS',
  'budget': 4000000,
  'domgross': nan,
  'intgross': 442550.0,
  'code': '2011PASS',
  'budget_2013$': 4142763,
  'domgross_2013$': nan,
  'intgross_2013$': 458345.0,
  'period code': 1.0,
  'decade code': 1.0},
... ]

标签: pythondictionarynan

解决方案


dictionary.values()是字典中所有值的生成器。您需要调用math.isnan()各个值。您可以使用它any()来执行此操作:

def remove_dictionarries_missing_data(list_of_dictionaries):
    return [d for d in list_of_dictionaries 
             if not any(isinstance(val, float) and math.isnan(val) for val in d.values())]

推荐阅读