从python的嵌套字典中删除nan

时间:2019-03-18 19:16:53

标签: python dictionary

从python的嵌套字典中删除NaN值。我的嵌套字典如下所示:

my_dict = {'abc':{'a':0.987, 'b':0.765, 'c': numpy.nan}, 'mda':{'a':0.145, 'b':0.584, 'e':numpy.nan}, 'fop':{'a':0.145, 'b': numpy.nan, 'c':0.485}}

我想从嵌套的字典中删除Nan值,预期结果如下:

my_dict = {'abc':{'a':0.987, 'b':0.765}, 'mda':{'a':0.145, 'b':0.584}, 'fop':{'a':0.145, 'c':0.485}}

我写了下面的代码从嵌套字典中删除Nan:

def remove_nan_from_dict(my_dict):
    new_dict = {}
    original_dict = collections.defaultdict()
    from math import isnan
    for k, v in my_dict.items():
        for k1, v1 in v.items():
            print(v1)
            if not isnan(v1):
                new_dict[k1] = v1
            print(new_dict)
        original_dict[k] = new_dict
        # print(original_dict.items())
    return original_dict

但要进入字典以下

defaultdict(None, {'abc': {'a': 0.145, 'b': 0.584, 'c': 0.485}, 'mda': {'a': 0.145, 'b': 0.584, 'c': 0.485}, 'fop': {'a': 0.145, 'b': 0.584, 'c': 0.485}})

3 个答案:

答案 0 :(得分:1)

您可以在此处使用字典理解,然后检查该值是否为np.nan


new_dict = {k: {a: b for a, b in v.items() if not np.isnan(b)} for k, v in my_dict.items()}

答案 1 :(得分:1)

您可以使用以下2个简单的循环:

my_dict = {'abc':{'a':0.987, 'b':0.765, 'c': numpy.nan}, 'mda':{'a':0.145, 'b':0.584, 'e':numpy.nan}, 'fop':{'a':0.145, 'b': numpy.nan, 'c':0.485}}

for items in my_dict:

    get_key = my_dict[items]

    for key, values in get_key.copy().items():
        if numpy.isnan(values):
            del get_key[key]
my_dict
> {'abc': {'a': 0.987, 'b': 0.765},
 'mda': {'a': 0.145, 'b': 0.584},
 'fop': {'a': 0.145, 'c': 0.485}}

答案 2 :(得分:0)

我有一个三层嵌套词典,所以我使用了以下内容:

import numpy as np    
for k, v in your_dict.items():
    for kk, vv in your_dict[k].items():
        for kkk, vvv in your_dict[k][kk].items():
            get_key = your_dict[k][kk][kkk]
            print(get_key)
            for kkkk, vvvv in get_key.copy().items():
                if np.isnan(vvvv):
                    del get_key[kkkk]