【问题标题】:Moving window in Pandas to check for the specific range values在 Pandas 中移动窗口以检查特定范围值
【发布时间】:2018-08-02 08:28:18
【问题描述】:

我有我的时间序列数据,我想在 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

【问题讨论】:

    标签: python pandas numpy time-series


    【解决方案1】:

    我想这样的东西应该更短,但想法是一样的:

    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
    

    【讨论】:

      【解决方案2】:

      对@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 时通过成对比较来减少比较次数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-02
        • 2012-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-20
        • 1970-01-01
        相关资源
        最近更新 更多