python - 如何从列表中删除具有 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},
... ]
解决方案
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())]
推荐阅读
- python - 子进程是否使用错误版本的 Python 来运行 Ansible?
- javascript - SVG 定义的文本标签中的可变文本
- r - R:强制回归系数加起来为 1
- firebase - 需要知道如何在 Angular 8 中从 firebase 检索嵌套数据
- performance - Elasticsearch 中酒店可用性数据的聚合性能问题
- ansible - 根据满足条件 Ansible 填充变量
- java - 需要帮助,所以它的字符总数更少
- javascript - 动态创建元素时Javascript事件处理程序消失
- android-studio - Dart Map 和解析 JSON
- html - 使用剪辑路径时隐藏的图像和标题:多边形 HTML/CSS