使用to_dict()我想出了以下字典。我需要放弃所有的纳米值。这种方法不起作用,因为它在迭代期间改变了大小。还有另一种方法可以实现这个目标吗?
{'k': {'a': nan, 'b': 1.0, 'c': 1.0},
'u': {'a': 1.0, 'b': nan, 'c': 1.0},
'y': {'a': nan, 'b': 1.0, 'c': nan}}
In [196]:
for listing, rate in master_dict.items():
for key in rate:
if pd.isnull(master_dict[listing][key]) == True:
del master_dict[listing][key]
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-200-8859eb717bb9> in <module>()
1 for listing, rate in master_dict.items():
----> 2 for key in rate:
3 if pd.isnull(master_dict[listing][key]) == True:
4 del master_dict[listing][key]
5
RuntimeError: dictionary changed size during iteration
答案 0 :(得分:2)
您可以使用pandas.notnull
或pandas.isnull
进行过滤的dict comprehension
加倍:
y = {k1:{k:v for k,v in v1.items() if pd.notnull(v)} for k1, v1 in d.items()}
print (y)
{'k': {'c': 1.0, 'b': 1.0}, 'u': {'c': 1.0, 'a': 1.0}, 'y': {'b': 1.0}}
类似的解决方案:
y = {k1:{k:v for k,v in v1.items() if not pd.isnull(v)} for k1, v1 in d.items()}
print (y)
{'k': {'c': 1.0, 'b': 1.0}, 'u': {'c': 1.0, 'a': 1.0}, 'y': {'b': 1.0}}
答案 1 :(得分:1)
代码的增量修复将是:
for key in list(rate.keys()): # make a copy and Python won't complain
更加pythonic的解决方案是使用dict compenhension删除项目:
for listing, rate in master_dict.items():
master_dict[listing] = {k: v for k, v in rate.items() if pd.notnull(v)}