在大熊猫中移动窗口以检查特定范围值



我有我的时间序列数据,我想在t 5和t-5的窗口中检查数据,然后检查它是否在0.1和5之间,然后需要标记那个时间为1,同样,如果同一窗口中的值大于5,则应返回2 else返回零。

我已经尝试过这样的尝试,如果有更有效的方法可以做到这一点。

def my_func(arr,thres=5,lwthres=0.1):
    arr=arr.astype(float)
    if((arr[0]<thres) & (arr[1]<thres) & (arr[2]<thres) &(arr[3]<thres) &(arr[4]<thres)
       &(arr[5]<thres)&(arr[6]<thres)&(arr[7]<thres)&(arr[8]<thres)&(arr[9]<thres)
       & (arr[0]>=lwthres) & (arr[1]>=lwthres) & (arr[2]>=lwthres) &(arr[3]>=lwthres)
       & (arr[4]>lwthres) &(arr[5]>=lwthres)&(arr[6]>=lwthres)&(arr[7]>=lwthres)&(arr[8]>=lwthres)&(arr[9]>=lwthres)):
        return 1   
    elif((arr[0]>=thres) & (arr[1]>=thres) & (arr[2]>=thres) &(arr[3]>=thres) &(arr[4]>=thres) &(arr[5]>=thres)&(arr[6]>=thres)&(arr[7]>=thres)&(arr[8]>=thres)&(arr[9]>=thres)):        
        return 2
    else:
        return 0
my_data=np.random.randint(5,size=100000)
my_df=pd.DataFrame(my_data)
tp=my_df.rolling(window=10,center=True).apply(lambda x:my_func(x))
df=pd.DataFrame()
df['value']=my_data
df['Type']=tp

我想这样的东西应该较短,但是想法是相同的:

def my_func(arr,thres=5,lwthres=0.1):
    arr=arr.astype(float)
    if(max(arr[0]<thres) & min(arr)>=lwthres):
        return 1   
    elif(min(arr)>=thres)):        
        return 2
    else:
        return 0

对 @alex的答案的改进是仅在第一次计算数组的min_value

def my_func(arr, thres=5, lwthres=0.1):
    arr=arr.astype(float)
    min_value, max_value = np.inf, np.NINF
    for i in arr:
        if i < min_value:
            min_value = i
        if i > max_value:
            max_value = i
    if min_value >= thres:
        return 2
    elif max_value < lwthres:
        return 0
    else:
        return 1

进一步的改进是通过成对比较min_valuemax_value时减少比较数量。

最新更新