python - 从字典中删除 NaN - Python
问题描述
我想从我的字典中删除 NaN。
my_dict = {'House': ['has keys',
'check lights',
nan,
nan,
nan],
'The Office': ['reading',
nan,
nan,
nan,
'coffee breaks']}
我相信 NaN 是浮点数,而不是字符串。我努力了:
import math
my_dict['House'] = [
x
for x in dict2['House']
if not (isinstance(x, float) and math.isnan(x))
]
我得到:
my_dict = {'House': ['has keys',
'check lights',],
'The Office': ['reading',
nan,
nan,
nan,
'coffee breaks']}
我希望它看起来像下面这样,但我不知道如何让我的 for 循环遍历所有键而不仅仅是 House:
my_dict = {'House': ['has keys',
'check lights'],
'The Office': ['reading',
'coffee breaks']}
解决方案
这应该有效,它将过滤字典中的所有值,删除 NaN 数字:
{ k: [x for x in v if not isinstance(x, float) or not math.isnan(x)] for k, v in my_dict.items() }
这是结果:
{'House': ['has keys', 'check lights'],
'The Office': ['reading', 'coffee breaks']}