Python中基于移动均值的异常值检测

2023-12-14

我正在尝试将算法从 MATLAB 转换为 Python。该算法适用于大型数据集,并且需要应用异常值检测和消除技术。

在MATLAB代码中,我使用的异常值删除技术是移动中位数:

   Outlier_T=isoutlier(Data_raw.Temperatura,'movmedian',3);
   Data_raw(find(Outlier_T),:)=[]

通过查找不成比例的值,用滚动中位数检测异常值位于三值移动窗口的中心。因此,如果我在第 3 行有一个值为 40 的“Temperatura”列,则会检测到该列并删除整行。

         Temperatura     Date       
    1        24.72        2.3        
    2        25.76        4.6        
    3        40           7.0        
    4        25.31        9.3        
    5        26.21       15.6
    6        26.59       17.9        
   ...        ...         ...

据我了解,这是通过pandas.DataFrame.rolling。我已经看到几篇文章举例说明了它的用法,但我无法使其与我的代码一起使用:

尝试A:

Dataframe.rolling(df["t_new"]))

尝试B:

df-df.rolling(3).median().abs()>200

#基于@Ami Tavory 的answer

我在这里遗漏了一些明显的东西吗?这样做的正确方法是什么? 感谢您的时间。


下面的代码根据阈值删除行。该阈值可以根据需要进行调整。但不确定它是否复制 Matlab 代码。

# Import Libraries
import pandas as pd
import numpy as np

# Create DataFrame
df = pd.DataFrame({
    'Temperatura': [24.72, 25.76, 40, 25.31, 26.21, 26.59],
    'Date':[2.3,4.6,7.0,9.3,15.6,17.9]
})

# Set threshold for difference with rolling median
upper_threshold = 1
lower_threshold = -1

# Calculate rolling median
df['rolling_temp'] = df['Temperatura'].rolling(window=3).median()

# Calculate difference
df['diff'] = df['Temperatura'] - df['rolling_temp']

# Flag rows to be dropped as `1`
df['drop_flag'] = np.where((df['diff']>upper_threshold)|(df['diff']<lower_threshold),1,0)

# Drop flagged rows
df = df[df['drop_flag']!=1]
df = df.drop(['rolling_temp', 'rolling_temp', 'diff', 'drop_flag'],axis=1)

Output

print(df)

   Temperatura  Date
0        24.72   2.3
1        25.76   4.6
3        25.31   9.3
4        26.21  15.6
5        26.59  17.9
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python中基于移动均值的异常值检测 的相关文章

随机推荐