Art*_*nko 1 python dictionary pandas
使用 to_dict() 我想出了以下字典。我需要删除所有 nan 值。这种方法不起作用,因为它在迭代过程中改变了大小。有没有另一种方法来实现这一点?
{'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
Run Code Online (Sandbox Code Playgroud)
您可以使用 doubledict comprehension与过滤器pandas.notnull或pandas.isnull:
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}}
Run Code Online (Sandbox Code Playgroud)
类似的解决方案:
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}}
Run Code Online (Sandbox Code Playgroud)