python - 使用滚动标准差检测 Pandas 数据框中的异常值

标签 python pandas dataframe standard-deviation outliers

我有一个用于快速傅里叶变换信号的数据帧。

有一列表示以 Hz 为单位的频率,另一列表示相应的幅度。

我读过几年前发表的一篇文章,您可以使用一个简单的 bool 函数来排除或仅包含最终数据框中高于或低于几个标准差的异常值。

df = pd.DataFrame({'Data':np.random.normal(size=200)})  # example dataset of normally distributed data. 
df[~(np.abs(df.Data-df.Data.mean())>(3*df.Data.std()))] # or if you prefer the other way around

问题是,当频率增加到 50 000 Hz 时,我的信号会下降几个数量级(最多小 10 000 倍)。因此,我无法使用仅导出高于 3 个标准差的值的函数,因为我只会从前 50 Hz 中选取“峰值”异常值。

有没有办法可以导出数据框中超过滚动平均值 3 个滚动标准差的异常值?

最佳答案

这也许可以通过一个简单的例子来最好地说明。基本上,您将现有数据与新列进行比较,该新列是滚动平均值加上三个标准差,也是滚动的。

import pandas as pd
import numpy as np
np.random.seed(123)
df = pd.DataFrame({'Data':np.random.normal(size=200)})

# Create a few outliers (3 of them, at index locations 10, 55, 80)
df.iloc[[10, 55, 80]] = 40.    

r = df.rolling(window=20)  # Create a rolling object (no computation yet)
mps = r.mean() + 3. * r.std()  # Combine a mean and stdev on that object

print(df[df.Data > mps.Data])  # Boolean filter
#     Data
# 55  40.0
# 80  40.0

要添加仅对异常值进行过滤的新列,而其他地方则使用 NaN:

df['Peaks'] = df['Data'].where(df.Data > mps.Data, np.nan)

print(df.iloc[50:60])
        Data  Peaks
50  -1.29409    NaN
51  -1.03879    NaN
52   1.74371    NaN
53  -0.79806    NaN
54   0.02968    NaN
55  40.00000   40.0
56   0.89071    NaN
57   1.75489    NaN
58   1.49564    NaN
59   1.06939    NaN

这里.where返回

An object of same shape as self and whose corresponding entries are from self where cond is True and otherwise are from other.

关于python - 使用滚动标准差检测 Pandas 数据框中的异常值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46796265/

相关文章:

python - 在文件中保存并读取 `\r` - Python 3

python - 无法 reshape numpy 数组

删除 ggplot 上未使用的月份

python - 将行追加到现有的 pandas 数据框

python - 插入不适用于 SQLAlchemy 数据库 session

python - 异常处理: Differentiating between instances of the same error in Python

python - 创建唯一的Id,读取多个文件时枚举不同的行值

python - 我该如何解决 - TypeError : cannot safely cast non-equivalent float64 to int64?

python - 使用阈值 pandas 数据框选择值

python - 如何将 DF 中的字段解析为月、日、年、小时和工作日?