Python 如何检查包含 NaN 的列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20319813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:11:22  来源:igfitidea点击:

How to Check list containing NaN

python

提问by user1234440

In my for loop, my code generates a list like this one:

在我的 for 循环中,我的代码生成了一个这样的列表:

list([0.0,0.0]/sum([0.0,0.0]))

The loop generates all sort of other number vectors but it also generates [nan,nan], and to avoid it I tried to put in a conditional to prevent it like the one below, but it doesn't return true.

该循环生成各种其他数字向量,但它也会生成[nan,nan],为了避免它,我尝试放入一个条件来防止它,如下所示,但它没有返回 true。

nan in list([0.0,0.0]/sum([0.0,0.0]))
>>> False

Shouldn't it return true?

它不应该返回true吗?

enter image description here

enter image description here

Libraries I've loaded:

我加载的库:

import PerformanceAnalytics as perf
import DataAnalyticsHelpers
import DataHelpers as data
import OptimizationHelpers as optim
from matplotlib.pylab import *
from pandas.io.data import DataReader
from datetime import datetime,date,time
import tradingWithPython as twp
import tradingWithPython.lib.yahooFinance as data_downloader # used to get data from yahoo finance
import pandas as pd # as always.
import numpy as np
import zipline as zp
from scipy.optimize import minimize
from itertools import product, combinations
import time
from math import isnan

采纳答案by DSM

I think this makes sense because of your pulling numpyinto scope indirectly via the star import.

我认为这是有道理的,因为您numpy通过星形导入间接进入了范围。

>>> import numpy as np
>>> [0.0,0.0]/0
Traceback (most recent call last):
  File "<ipython-input-3-aae9e30b3430>", line 1, in <module>
    [0.0,0.0]/0
TypeError: unsupported operand type(s) for /: 'list' and 'int'

>>> [0.0,0.0]/np.float64(0)
array([ nan,  nan])

When you did

当你做

from matplotlib.pylab import *

it pulled in numpy.sum:

它拉进来numpy.sum

>>> from matplotlib.pylab import *
>>> sum is np.sum
True
>>> [0.0,0.0]/sum([0.0, 0.0])
array([ nan,  nan])

You can test that thisnanobject (nanisn't unique in general) is in a list via identity, but if you try it in an arrayit seems to test via equality, and nan != nan:

您可以通过身份测试nan对象(nan通常不是唯一的)是否在列表中,但是如果您在一个列表中尝试array它似乎通过相等性进行测试,并且nan != nan

>>> nan == nan
False
>>> nan == nan, nan is nan
(False, True)
>>> nan in [nan]
True
>>> nan in np.array([nan])
False

You could use np.isnan:

你可以使用np.isnan

>>> np.isnan([nan, nan])
array([ True,  True], dtype=bool)
>>> np.isnan([nan, nan]).any()
True

回答by samrap

You should use the mathmodule.

您应该使用该math模块。

>>> import math
>>> math.isnan(item)

回答by AbhishekLohade

May be this is what you are looking for...

可能这就是你正在寻找的......

a = [2,3,np.nan]
b = True if True in np.isnan(np.array(a)) else False
print(b)