簡體   English   中英

計算熊貓滾動窗口中的特定值

[英]Count specific value in pandas rolling window

我有一個包含數千行的數據框。 一列僅包含 3 個值:-1、0、1。我想在滾動窗口(假設為 100)中計算特定值(假設為 0)出現的次數。

我該怎么做? 我沒有看到與對象滾動相關的這種方法,我不知道如何通過應用來實現。

這很簡單,我編寫了一個快速演示。 你應該明白了。

例子

# Parameters
# iterable - column
# size - window size (100)

def window(iterable, size=2):
    i = iter(iterable)
    win = []
    for e in range(0, size):
        win.append(next(i))
    yield win
    for e in i:
        win = win[1:] + [e]
        yield win

# Sample data
a = [1, 0, 0, 0, 1, 1]

from collections import Counter

result = []
value = 1 # Value to keep count (-1, 0, 1)

for i in window(a, 2):
    count = Counter(i)[value]
    result.append(count)

# Sample output
print(result)
[1, 0, 0, 1, 2]

我想這會有所幫助。 我測試了這個,它有效

def cnt(x):
     prev_count = 0
     for i in x:
         if i == 0:
             prev_count+=1
     return prev_count

df['col'].rolling(100,min_periods=1).apply(cnt)

暫無
暫無

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

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