gpt4 book ai didi

python - Pandas:如何检测数据框中的峰值点(异常值)?

转载 作者:太空狗 更新时间:2023-10-30 02:53:04 26 4
gpt4 key购买 nike

我有一个 pandas 数据框,其中有几个速度值在不断移动,但它是一个传感器数据,所以我们经常在中间的某些点出现错误,移动平均线似乎也无济于事,所以呢我可以使用哪些方法从数据中删除这些异常值或峰值点?

例子:

data points = {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}

在此数据中,如果我看到点 4、4、5、6 完全是离群值,在我使用带有 5 分钟窗口框架的滚动平均值来平滑这些值之前,但我仍然得到这些类型的很多 blip 点,我想删除它们,任何人都可以建议我任何技术来摆脱这些点.

我有一张更清晰的数据 View 图像: enter image description here

如果您在这里看到数据如何显示一些我必须删除的离群点?任何想法摆脱这些点的可能方法是什么?

最佳答案

我真的认为 z-score 使用 scipy.stats.zscore()是去这里的路。查看this post中的相关问题.在那里,他们专注于移除潜在异常值之前使用哪种方法。在我看来,您的挑战要简单一些,因为根据提供的数据判断,无需转换数据即可非常直接地识别潜在异常值。下面是执行此操作的代码片段。不过请记住,什么看起来像异常值,什么看起来不像异常值,将完全取决于您的数据集。在移除一些异常值之后,以前看起来不像异常值的东西现在突然变成了异常值。看看:

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)

原始数据:

enter image description here

测试运行 1:Z-score = 4:

enter image description here

如您所见,由于级别设置得太高,因此没有删除任何数据。

测试运行 2:Z-score = 2:

enter image description here

现在我们有所进展。两个异常值已被删除,但仍有一些可疑数据。

测试运行 3:Z-score = 1.2:

enter image description here

这看起来真不错。剩余的数据现在似乎比以前分布得更均匀一些。但是现在原始数据点突出显示的数据点开始看起来有点像潜在的异常值。那么在哪里停下来呢?这将完全取决于您!

编辑:这是一个简单的复制和粘贴的全部内容:

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')

关于python - Pandas:如何检测数据框中的峰值点(异常值)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51006163/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com