从字典中删除NaN-Python

时间:2019-05-12 11:47:47

标签: python pandas

我想从字典中删除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']}

4 个答案:

答案 0 :(得分:1)

这应该起作用,它将过滤字典中的所有值,并删除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']}

答案 1 :(得分:1)

自从标记了 const params = new HttpParams().set("observe", "events"); 以来,您可以执行以下操作:

pandas

print(df)

          House     The Office
0      has keys        reading
1  check lights            NaN
2           NaN            NaN
3           NaN            NaN
4           NaN  coffee breaks

df_new=df.apply(lambda x: pd.Series(x.dropna().values))
print(df_new)

答案 2 :(得分:0)

您处在正确的轨道上,但是只选中“ house”,您需要将逻辑应用于所有按键:

import math
for tv_show in my_dict:
    my_dict[tv_show] = [
        x
        for x in dict2[tv_show]
        if not (isinstance(x, float) and math.isnan(x))
    ]

答案 3 :(得分:0)

您也可以采用其他方法,只保留字符串值(当然,只要您只需要字符串值):

>>> for k, v in my_dict.items():
>>>     my_dict[k] = [val for val in v if isinstance(val, str)]

>>> my_dict
# {'House': ['has keys', 'check lights'], 'The Office': ['reading', 'coffee breaks']}

即使这也可以在dictionary comprehension中实现,但我认为在这种情况下,单线逻辑有点密集,但是,它看起来像这样:

>>> {k: [val for val in v if isinstance(val, str)] for k, v in my_dict.items()}