简体   繁体   English

从字典中删除NaN-Python

[英]Removing NaNs from dictionary - Python

I would like to remove the NaNs from my dictionary. 我想从字典中删除NaN。

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

I believe the NaNs are floats, not strings. 我相信NaN是浮点数,而不是字符串。 I have tried: 我努力了:

import math

my_dict['House'] = [
    x
    for x in dict2['House']
    if not (isinstance(x, float) and math.isnan(x))
]

And I get: 我得到:

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

I would like it to look like the following, but I dont know how to get my for loop to loop through all keys instead of just House: 我希望它看起来像下面,但是我不知道如何让我的for循环遍历所有键,而不仅仅是House:

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

This should work, it'll filter all the values in the dictionary, removing NaN numbers: 这应该可行,它将过滤字典中的所有值,并删除NaN数字:

{ k: [x for x in v if not isinstance(x, float) or not math.isnan(x)] for k, v in my_dict.items() }

This is the result: 结果如下:

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

Since you have tagged pandas , you can do something like: 由于您已经标记了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)

          House     The Office
0      has keys        reading
1  check lights  coffee breaks

you are on the correct track, but you only check 'house', you need to apply your logic to all your keys: 您处在正确的轨道上,但是只选中“ 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))
    ]

You could also go the other way around and only retain string values (as long as you ONLY want string values, of course): 您也可以采用其他方法,只保留字符串值(当然,只要您只需要字符串值):

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

Even though this can also be achieved in a dictionary comprehension , I think the logic is a bit dense in this case for a one-liner, however, it would look like this: 即使这也可以通过字典理解来实现,但我认为在这种情况下,单行逻辑有点密集,但是,它看起来像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM