我有下面的数据帧,它是一个时间序列数据,我处理这些信息以输入到我的预测模型中。
df = pd.DataFrame({"timestamp": [pd.Timestamp('2019-01-01 01:00:00', tz=None),
pd.Timestamp('2019-01-01 01:00:00', tz=None),
pd.Timestamp('2019-01-01 01:00:00', tz=None),
pd.Timestamp('2019-01-01 02:00:00', tz=None),
pd.Timestamp('2019-01-01 02:00:00', tz=None),
pd.Timestamp('2019-01-01 02:00:00', tz=None),
pd.Timestamp('2019-01-01 03:00:00', tz=None),
pd.Timestamp('2019-01-01 03:00:00', tz=None),
pd.Timestamp('2019-01-01 03:00:00', tz=None)],
"value":[5.4,5.1,100.8,20.12,21.5,80.08,150.09,160.12,20.06]
})
由此,我取每个时间戳的值的平均值,并将该值作为输入发送到predictor。但目前,我只是使用阈值来过滤掉异常值,但这些阈值似乎过滤掉了真正的值,也没有过滤掉一些异常值。
例如,我一直在
df[(df['value']>3 )& (df['value']<120 )]
然后,这不会过滤掉
2019-01-01 01:00:00 100.8
它是该时间戳的异常值,并且确实过滤掉了
2019-01-01 03:00:00 150.09
2019-01-01 03:00:00 160.12
它们不是该时间戳的异常值。
那么,我如何根据哪个时间戳不适合该组来过滤掉每个时间戳的异常值?
任何帮助都是非常感谢的。
发布于 2020-06-18 12:23:30
好吧,让我们假设您正在搜索置信区间以检测异常值。
然后,您必须获得每个时间戳组的平均值和置信区间。因此您可以使用run
stats = df.groupby(['timestamp'])['value'].agg(['mean', 'count', 'std'])
ci95_hi = []
ci95_lo = []
import math
for i in stats.index:
m, c, s = stats.loc[i]
ci95_hi.append(m + 1.96*s/math.sqrt(c))
ci95_lo.append(m - 1.96*s/math.sqrt(c))
stats['ci95_hi'] = ci95_hi
stats['ci95_lo'] = ci95_lo
df = pd.merge(df, stats, how='left', on='timestamp')
这将导致以下输出:
然后您可以调整筛选器列:
import numpy as np
df['Outlier'] = np.where(df['value'] >= df['ci95_hi'], 1, np.where(df['value']<= df['ci95_lo'], 1, 0))
那么列异常值中有1的所有元素都是异常值。您可以使用1.96来调整这些值,以便稍微使用它。
结果看起来像这样:
https://stackoverflow.com/questions/62424181
复制