我有我的时间序列数据,我想检查t+5和t-5的窗口中的数据,检查它是否在0.1和5之间,然后需要将该时间标记为1,同样,如果同一窗口中的值大于5,那么它应该返回2,否则返回0。在
我已经试过了,请问有没有更有效的方法。在
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
我想这样的东西应该短一点,但想法是一样的:
与@Alex的答案相比,一个改进是只第一次计算数组的
min_value
。在进一步的改进是通过成对比较来减少计算}时的比较次数。在
min_value
和{相关问题 更多 >
编程相关推荐