在我的for循环中,我的代码会生成一个像这样的列表:
list([0.0,0.0]/sum([0.0,0.0]))
循环生成所有类型的其他数字向量,但它也生成[nan,nan]
,并且为了避免它,我试图放入条件以防止它像下面那样,但它不会返回true。
nan in list([0.0,0.0]/sum([0.0,0.0]))
>>> False
不应该归还吗?
我已加载的库:
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
答案 0 :(得分:17)
我认为这是有道理的,因为您通过星号导入间接地将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])
当你做了
from matplotlib.pylab import *
它进入了numpy.sum
:
>>> from matplotlib.pylab import *
>>> sum is np.sum
True
>>> [0.0,0.0]/sum([0.0, 0.0])
array([ 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
:
np.isnan
答案 1 :(得分:4)
您应该使用math
模块。
>>> import math
>>> math.isnan(item)
答案 2 :(得分:0)
也许这就是您要寻找的...
a = [2,3,np.nan]
b = True if True in np.isnan(np.array(a)) else False
print(b)