如何忽略inf并在for循环中移动到下一个迭代

2024-09-27 09:31:22 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我希望得到一些帮助,我对python还很陌生,我想知道如何设置一个条件,以便在数据中遇到-inf,那么程序将循环到下一个迭代

import numpy as np
import math
import matplotlib.pylab as plt
import pandas as pd
from scipy.interpolate import interp1d
from scipy.signal import butter, filtfilt
from scipy import interpolate
Ic = 400
lower_Ig = 720 #the lower limit of the generator current Ig
Upper_Ig = 1040 #Upper limit
Ix=range(-60,61,1)
for j in range(40, 80, 10):
    Var=(40000* j)/ 10000
    #print Var
    for c in range(lower_Ig, Upper_Ig+1, 40):
        #print c
        Names =['Vg','V3', 'V4']
        Data = pd.read_csv('/Documents/JTL_'+str(Var)+'/Ig='+str(c)+'/Grey_Zone.csv', names=Names)
        Vg = Data['Vg']
        V3 = Data['V3']
        V4 = Data ['V4']
        Prf = V4 / Vg
        #print Prf
        C = 0.802
        freq = 100
        b, a = butter(2, (5/C)/(freq/2), btype = 'low')
        yg = filtfilt(b, a, Vg)  # filter with phase shift correction
        y4 = filtfilt(b, a, V4)  # filter with phase shift correction
        SW = y4 / yg
        if SW == np.nan: #I need a condition here that if -inf is encountered then the programme should loop to next c value in for loop 
            continue 
            f = interp1d( SW, Ix )
            print f(0.25), f(0.5), f(0.75)
            print f(0.75)-f(0.25)

我尝试过使用不同的numpy函数,但总是得到相同的错误

^{pr2}$

我不认为我可以使用any()或{},因为这将只包含所有数据,我想忽略-inf。任何帮助都将不胜感激


Tags: thefromimportdataasrangescipyupper
2条回答

假设在循环的一次迭代中有SW,如下所示:

>>> import numpy as np
>>> SW = [np.inf, -np.inf, np.nan, 0, 1]
>>> np.isfinite(SW)
[False, False, False, True, True]
>>> all(np.isfinite(SW))
False   # since one or more in the list is False

如果您想跳过任何SWnan, inf, -inf,您可以使用

^{pr2}$

如果nan不是问题,只有-inf是问题,那么您可以使用

if any(np.isneginf(SW)):
   continue

如果SW的任何元素是-inf,则将跳过迭代

注意,不能使用==和{}比较相等性

>>> x = np.nan
>>> x == np.nan
False

而是使用isnan

>>> np.isnan(x)
True

您可以filter去掉不需要的元素(例如newlist=filter(lambda n: not numpy.isneginf(n), list_of_numbers)),或者使用numpy.nan_to_num(...)转换成一个正确的数字列表。在

相关问题 更多 >

    热门问题