【发布时间】:2021-04-27 13:59:06
【问题描述】:
如果PC_list 数组越过Upper 或Lower 边界,我希望代码打印为true。我本质上是在尝试将 vanilla python 代码转换为 numpy 版本,所以它更快。 if 函数查找 PC_list 是否跨越了上或下 numpy 数组。虽然运行 numpy.select 函数时出现索引超出边界错误。 IndexError: index 25 is out of bounds for axis 0 with size 25
numpy 版本:
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')
香草python版本:
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")
【问题讨论】:
-
您能否详细解释一下您认为这些长期条件在做什么?某些运算符优先级看起来不太正确。
-
你为什么要做
Upper = np.random.rand(1,25)只是为了在几行之后将其设置为常数? -
能否提供样例输入输出?
-
看
choices。我希望它是[None,None]。select不是条件操作。相反,它返回一个数组,其值来自choices。您需要逐步测试此代码。
标签: python numpy loops indexing range