我真的认为使用scipy.stats.zscore() 的z-score 是这里的方法。查看this post 中的相关问题。在那里,他们专注于在删除潜在异常值之前使用哪种方法。在我看来,您的挑战有点简单,因为从提供的数据来看,无需转换数据即可识别潜在的异常值非常简单。下面是一个代码 sn-p 就是这样做的。但请记住,什么看起来像异常值和看起来不像异常值将完全取决于您的数据集。在移除 一些 异常值之后,以前看起来不像异常值的东西,现在突然变得如此。看看:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from scipy import stats
# your data (as a list)
data = [0.5,0.5,0.7,0.6,0.5,0.7,0.5,0.4,0.6,4,0.5,0.5,4,5,6,0.4,0.7,0.8,0.9]
# initial plot
df1 = pd.DataFrame(data = data)
df1.columns = ['data']
df1.plot(style = 'o')
# Function to identify and remove outliers
def outliers(df, level):
# 1. temporary dataframe
df = df1.copy(deep = True)
# 2. Select a level for a Z-score to identify and remove outliers
df_Z = df[(np.abs(stats.zscore(df)) < level).all(axis=1)]
ix_keep = df_Z.index
# 3. Subset the raw dataframe with the indexes you'd like to keep
df_keep = df.loc[ix_keep]
return(df_keep)
原始数据:
测试运行 1:Z 分数 = 4:
如您所见,没有数据被删除,因为级别设置得太高了。
测试运行 2:Z 分数 = 2:
现在我们正在取得进展。两个异常值已被移除,但仍有一些可疑数据。
测试运行 3:Z 分数 = 1.2:
这看起来真的很好。剩下的数据现在似乎比以前分布得更均匀了。但现在原始数据点突出显示的数据点开始看起来有点像潜在的异常值。那么该停在哪里呢?这完全取决于您!
编辑:这是一个简单的复制和粘贴的全部内容:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from scipy import stats
# your data (as a list)
data = [0.5,0.5,0.7,0.6,0.5,0.7,0.5,0.4,0.6,4,0.5,0.5,4,5,6,0.4,0.7,0.8,0.9]
# initial plot
df1 = pd.DataFrame(data = data)
df1.columns = ['data']
df1.plot(style = 'o')
# Function to identify and remove outliers
def outliers(df, level):
# 1. temporary dataframe
df = df1.copy(deep = True)
# 2. Select a level for a Z-score to identify and remove outliers
df_Z = df[(np.abs(stats.zscore(df)) < level).all(axis=1)]
ix_keep = df_Z.index
# 3. Subset the raw dataframe with the indexes you'd like to keep
df_keep = df.loc[ix_keep]
return(df_keep)
# remove outliers
level = 1.2
print("df_clean = outliers(df = df1, level = " + str(level)+')')
df_clean = outliers(df = df1, level = level)
# final plot
df_clean.plot(style = 'o')