【问题标题】:Count specific value in pandas rolling window计算熊猫滚动窗口中的特定值
【发布时间】:2021-02-10 21:55:11
【问题描述】:

我有一个包含数千行的数据框。一列仅包含 3 个值:-1、0、1。我想在滚动窗口(比如 100)中计算特定值(比如 0)出现的次数。

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

【问题讨论】:

  • 这是一种方法:迭代行并设置计数器列表和计数器 = 0,当 df 的索引达到每 100 时,追加到列表,并将计数器设置为 0 . 至于获取值(我猜它在 df 中的字符串中),可能必须使用正则表达式,或者在 apply(lambda x: x.split(',')) 的帮助下将它们拆分到一个列表中检查列表中是否为 0。
  • 它有什么样的索引?请包括df['thecolumn'].head(7)

标签: python pandas dataframe rolling-computation


【解决方案1】:

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

示例

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

【讨论】:

    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 2018-07-10
      • 2017-03-30
      • 1970-01-01
      • 2018-09-02
      • 2023-01-31
      • 2023-01-25
      • 2020-04-21
      • 2021-03-30
      • 2020-03-26
      相关资源
      最近更新 更多