gpt4 book ai didi

python - 从字典中的字典中删除 NaN(Dict 在运行时错误期间更改大小)

转载 作者:太空宇宙 更新时间:2023-11-04 09:59:12 24 4
gpt4 key购买 nike

使用 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

最佳答案

您可以使用双重 dict comprehensionpandas.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}}

类似的解决方案:

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}}

关于python - 从字典中的字典中删除 NaN(Dict 在运行时错误期间更改大小),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44569021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com