Skip to main content
 首页 » 编程设计

python之Pandas 滚动窗口之标记值

2025年01月19日8jpfss

在 pandas 数据框中,我想过滤某些列稳定在 10.0 个单位以内的行。

def abs_delta_fn(window): 
   x = window[0]             
   for y in window[1:]: 
      if abs(x-y) > 10.0: 
         return False             
      return True 
 
df['filter']= df['column'].rolling(5, min_periods=5).apply(abs_delta) 

所以,如果 a 有这样的 df

1   0 
2   20 
3   40 
4   40 
5   40 
6   40 
7   40 
8   90 
9   120 
10  120 

应用我得到的滚动窗口:

1   0     nan 
2   20    nan 
3   40    nan 
4   40    nan 
5   40    False 
6   40    False 
7   40    True 
8   90    False 
9   120   False 
10  120   False 

我怎样才能以一种聪明的方式得到它?

1  0     nan (or False) 
2  20    nan (or False) 
3  40    True 
4  40    True 
5  40    True 
6  40    True 
7  40    True 
8  90    False 
9  120   False 
10 120   False 

请您参考如下方法:

IIUC,你已经知道了rolling,只是在后面加上apply,这里的关键是.iloc[::-1],因为滚动是从当前行向上看(向后),但你需要向前

s=df.x.iloc[::-1].rolling(5,min_periods=5).apply(lambda x : (abs((x-x[0]))<10).all()) 
df.loc[df.index.difference(sum([list(range(x, x+5))for x in s[s==1].index.values],[]))] 
 
Out[1119]:  
      x 
1     0 
2    20 
8    90 
9   120 
10  120