计算滚动风中的特定值

2024-04-26 20:27:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个几千行的数据帧。一列仅包含3个值:-1、0、1。我想在滚动窗口(假设100)中计算特定值(假设0)出现的次数。你知道吗

我该怎么做?我没有看到与对象滚动相关的这种方法,我也不知道如何通过应用来实现。你知道吗


Tags: 数据对象方法次数个值
1条回答
网友
1楼 · 发布于 2024-04-26 20:27:17

很简单,我编写了一个快速演示。你应该明白。你知道吗

示例

# 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]

相关问题 更多 >