Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

python - Turning and if and elif statement into numpy form

I want the code to print true if PC_list array crosses the Upper or Lower boundary. I am essentially trying to convert the vanilla python code to numpy version so it is faster. The if functions look for if the PC_list crosses the upper or lower numpy arrays. I get an index out of border error when the numpy.select function is run though. IndexError: index 25 is out of bounds for axis 0 with size 25

numpy version:

PC_list = np.random.rand(1,25)
Upper = np.random.rand(1,25) 
Lower = np.random.rand(1,25)

#Configs
Lower = 0.2  #Lower and upper boundary values 
Upper = 2
number = 10000   #used for calculations with stand deriv and linear reg
position_value = 0 
conditions= [
    ((PC_list[PC_x_list+1]<lower[Boundary_x_list+1]!=PC_list[PC_x_list]>lower[Boundary_x_list]|PC_list[PC_x_list+1]>lower[Boundary_x_list+1]!=PC_list[PC_x_list]<lower[Boundary_x_list])&(position_value==0|position_value==2))|((Boundary_x_list==Boundary_x_list[-2])&(position_value==0|position_value==2)),
    ((PC_list[PC_x_list+1]<upper[Boundary_x_list+1]!=PC_list[PC_x_list]>upper[Boundary_x_list]|PC_list[PC_x_list+1]<upper[Boundary_x_list+1]!=PC_list[PC_x_list]>upper[Boundary_x_list])&(position_value==0|position_value==1))|((Boundary_x_list==Boundary_x_list[-2])&(position_value==0|position_value==1))
    
]

choices = [
    print("lower cross"),
    print("upper cross")
    
]

np.select(conditions, choices, default = 'NA')

Vanilla python version:

for i in range (len(PC_list)):
    if ((PC_list[i+number-1] < lower[i-1] != PC_list[i+number] > lower[i] or PC_list[i+number-1] > lower[i-1] != PC_list[i+number] < lower[i]) and (position_value==0 or position_value==2)) or ((i == len(PC_list)-number-1) and (position_value==0 or position_value==2)):         
        print("lower cross")    
    elif ((PC_list[(i+number)-1] < upper[i-1] != PC_list[i+number] > upper[i] or PC_list[(i+number)-1] < upper[i-1] != PC_list[i+number] > upper[i]) and (position_value==0 or position_value==1)) or ((i == len(PC_list)-number-1) and (position_value==0 or position_value==1)):
          print("upper cross")     

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...