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

标签 python scipy filtering signal-processing

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

我的只是一个由离散值组成的信号,例如 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()

Random data with median filtered signal in red.

其中红线是窗口大小为 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]

关于python - 我需要什么过滤器?只想保留高频值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32890967/

相关文章:

python - 在 Github 上的 jupyter 笔记本的表中显示管道

python - 带有 Unicode 项的 ConfigParser

python - 将 Dataframe 列中的列表拆分为特定的列名称

Python Sklearn.Model_Selection 给出无法导入梳子的错误

python - 使用 scipy.io.savemat() 时如何不覆盖 .mat 文件?

javascript - UIkit 3 的 Filter 组件 : Set active filter with URL hash - unable to change active filter with JS

从 key => 存储在字典中的值创建命令 args 字符串的 Pythonic 方法

python - spacy 的造轮子失败

excel - 使用另一列值过滤一列

python - 过滤python字典中的项目,其中键包含特定的字符串