簡體   English   中英

Pandas - 可變滾動 window

[英]Pandas - variable rolling window

我正在尋找創建一個迭代滾動過程以用於 pandas DataFrame,當滿足某些條件時停止。 具體來說,我希望 function 檢查 window 上的值的總和,並在總和的絕對值超過某個數量時停止。

x = np.random.randint(0,5,(100,))
df = pd.DataFrame(x, columns=["value"])
df_iter = pd.DataFrame(index=df.index)
max_iter = 5
threshold = 10

for i in range(2,max_iter+1):
    df_iter[i] = df["value"].rolling(i).sum()

match_indices = np.argmax(df_iter.abs().values>threshold, axis=1)

上面的方法到達那里,但有點笨拙,需要更多來說明未達到閾值的項目。

最終,我希望得到的只是一系列 [-1,0,1] 如果在最大 window 中超過正閾值,則每個項目將為 1,如果超過負閾值,則為 -1,否則為 0。 所以 output 如下所示。 請注意,由於滾動性質,這些項目往往以集群形式出現。 同樣,最重要的特征是找到最近發生的閾值被超過。

[0,1,1,1,0,0,-1,-1,-1,0,-1,-1,-1,-1,0,0,0,1,1,1,1]

那么有沒有辦法在 pandas 中進行滾動查找?

事實證明,使用 numpy 的cumsum function 相當容易。

data = np.random.randint(-10,10,(100,))
df = pd.DataFrame(data, columns=["value"])
max_n = 10
threshold = 10

def get_last_threshold(x):
    # reverse indexes and find cumulative sum for last max_n periods
    x = x.values[::-1].cumsum()
    # find first instance of absolute value of the cumulative sum above the threshold
    match = np.argmax(np.abs(x)>threshold) 
    # map to [-1,0,1] by getting sign of matching cumsums and filtering out items below threshold (np.argmax defaults to index 0 if no match found)
    signal = np.sign(x[match]) * (np.abs(x[match]) > threshold).astype(int)
    return signal

signals = df["value"].rolling(max_n, min_periods=1).apply(get_last_threshold).values
print(signals)

信號示例 output:

array([ 0.,  0.,  0., -1., -1., -1., -1., -1., -1., -1.,  1.,  1., -1.,
   -1.,  0.,  1.,  0.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  0.,
   -1., -1., -1.,  1., -1., -1., -1., -1., -1., -1.,  0.,  1.,  1.,
    1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  0., -1.,  0.,  1.,  0.,
   -1., -1., -1., -1., -1., -1., -1., -1.,  0.,  1.,  0.,  1.,  0.,
   -1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,
    1.,  1.,  1., -1., -1., -1., -1., -1., -1., -1.,  1.,  1.,  1.,
   -1., -1., -1.,  0.,  1.,  1.,  1.,  1.,  1.])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM