python使用箱型图剔除异常值的实现方法(十大少儿编程教育品牌)这样也行?

随心笔谈2年前发布 admin
191 0 0

文章摘要

这篇文章介绍了一种通过箱线图(Box Plot)方法判断数据异常点的Python函数。函数`box_outlier`对数据的每一列分别处理,计算下四分位数(Q1)、上四分位数(Q3)以及四分位极差(IQR),并根据 whisker 区间(上下边缘)确定异常点。异常点的索引被记录后删除,最终返回处理后的新数据。该方法通过四分位数计算异常点,适用于数据清洗和预处理。

# 箱型图判断异常点
def box_outlier(data):
df=data.copy(deep=True)
out_index=[]
for col in df.columns: # 对每一列分别用箱型图进行判断
Q1=df[col].quantile(q=0.25) # 下四分位
Q3=df[col].quantile(q=0.75) # 上四分位
low_whisker=Q1 – 1.5 * (Q3 – Q1) # 下边缘
up_whisker=Q3 + 1.5 * (Q3 – Q1) # 上边缘
# 寻找异常点,获得异常点索引值,删除索引值所在行数据
rule=(df[col] > up_whisker) | (df[col] < low_whisker)
out=df[col].index[rule]
out_index +=out.tolist()
df.drop(out_index, inplace=True)
return df

© 版权声明

相关文章