Skip to main content
 首页 » 编程设计

python之我需要什么过滤器只想保留高频值

2025年05月04日23rubylouvre

我问这个问题是因为我不太确定我应该使用哪个过滤器。

我的只是一个由离散值组成的信号,例如 s = [1 2 2 2 3 4 2 4 3 4 5 3 2 3 3]。然后我想根据窗口大小过滤信号。所以例如如果我为 s 使用 5 的窗口大小,那么我会得到; s_filtered = [2 2 2 2 2 4 4 4 4 4 3 3 3 3 3]。因此,我想保留每个 block 中频率最高的值。对于索引 0:4(窗口大小 5),最高频率的值为 2,所以我希望我的“过滤”信号(如果这确实是正确的术语)在所有索引 0:4 中有 2 个用于“过滤”信号.

目前我只使用中值滤波器,但我认为这不是正确的方法。

这里有一些 python 代码来演示我在做什么(但如前所述,我认为这是错误的)。

import numpy as np 
import pylab * 
from scipy.signal import medfilt 
 
test = np.random.randint(10, size=1000) 
 
fig, ax1 = plt.subplots(1,sharey=True, sharex=True, figsize=(15,5)) 
ax1.plot(test) 
ax1.plot(medfilt(test,[99]),'r') 
plt.show() 

其中红线是窗口大小为 99 的过滤信号。

解决方案:

import itertools 
import collections 
 
def grouper(iterable, n, fillvalue=None): 
    args = [iter(iterable)] * n 
    return itertools.izip_longest(*args, fillvalue=fillvalue) 
 
s = [1, 2, 2, 2, 3, 4, 2, 4, 3, 4, 5, 3, 2, 3, 3] 
 
list(chain.from_iterable(repeat(collections.Counter(x).most_common(1)[0][0],5) for x in grouper(s,5))) 

请您参考如下方法:

您可以使用 itertools recipes 中的 grouper 函数根据指定的长度对数组进行分组,然后使用 collections.Counter.most_common() 方法找到最常见的项目,并使用 itertools.repeat 将项目重复 5 次最后用 itertools.chain.from_iterable 链接重复的对象:

def grouper(iterable, n, fillvalue=None): 
    args = [iter(iterable)] * n 
    return zip_longest(*args, fillvalue=fillvalue) 

演示:

>>> list(chain.from_iterable(repeat(Counter(x).most_common(1)[0][0],5) for x in grouper(s,5))) 
[2, 2, 2, 2, 2, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3]