[英]How to disregard -inf and move to next iteration in for loop
您好,我希望對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函數,但始終遇到相同的錯誤
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
我不認為我可以使用any()
或all()
因為這將僅包括所有數據,並且我想忽略-inf。 任何幫助是極大的贊賞
假設在循環的一次迭代中有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
如果要跳過任何具有nan, inf, -inf
SW
,則可以使用
if not all(np.isfinite(SW)):
continue
如果nan
不是問題,只有-inf
,則可以使用
if any(np.isneginf(SW)):
continue
如果SW
任何元素為-inf
它將跳過迭代
請注意,您不能將==
與np.nan
進行相等性比較
>>> 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(...)
轉換為適當的數字列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.