Python异常值预警

该代码示例展示了如何基于3倍标准差(3sigma)原则检测数据中的异常值。首先,它读取了一个名为catering_sale.xls的Excel文件,从中提取销量和日期两列。接着,计算销量的平均值和标准差,设定阈值,并找出低于或高于阈值的异常销量数据点,将这些异常值和对应的日期记录下来。最后,用matplotlib可视化正常数据点和异常数据点,并对异常点进行标注。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#-*- coding: utf-8 -*-

#基于3sigma的异常值检测



import numpy as np

import pandas as pd

import matplotlib.pyplot as plt #导入绘图库



n = 3 # n*sigma



catering_sale =r"C:\Users\18703\Desktop\catering_sale.xls" #数据路径



data = pd.read_excel(catering_sale, index_col = False) #读取数据

data_y = data[u'销量']

data_x = data[u'日期']



ymean = np.mean(data_y)

ystd = np.std(data_y)

threshold1 = ymean - n * ystd

threshold2 = ymean + n * ystd



outlier = [] #将异常值保存

outlier_x = []



for i in range(0, len(data_y)):

    if (data_y[i] < threshold1)|(data_y[i] > threshold2):

        outlier.append(data_y[i])

        outlier_x.append(data_x[i])

    else:

        continue



print('\n异常数据如下:\n')

print(outlier)

print(outlier_x)

在这里插入图片描述

plt.plot(data_x, data_y)

plt.plot(outlier_x, outlier, 'ro')

for j in range(len(outlier)):

    plt.annotate(outlier[j], xy=(outlier_x[j], outlier[j]), xytext=(outlier_x[j],outlier[j])) #用于标注

plt.show()

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

rubyw

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值