Repository navigation
Expand file tree
/
Copy pathanomaly_detect.py
More file actions
60 lines (45 loc) · 2.41 KB
/
Copy pathanomaly_detect.py
File metadata and controls
60 lines (45 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import pandas as pd
def deviations_from_mean(data, values, group_by=None, window=5, sigma=1.96):
"""
"""
# verifying data is correct instance
assert isinstance(data,pd.DataFrame)
## checking that data entry is valid
if group_by not in data.columns.tolist() and group_by is not None:
raise KeyError('{} is not in the columns of the DataFrame object.'.format(group_by))
if values not in data.columns.tolist():
raise KeyError('{} is not in the columns of the DataFrame object.'.format(values))
# Initializing return data
df = pd.DataFrame()
if group_by is not None:
for name in data[group_by].unique().tolist():
temp = data.loc[data[group_by]==name,:].copy()
temp['rolling_mean'] = temp[values].rolling(window, min_periods=1).mean()
temp['resid'] = temp[values] - temp['rolling_mean']
## computing the rolling standard deviation on the residuals
temp['std'] = temp['resid'].rolling(window, min_periods=1).std()
temp['std'].fillna(temp['std'].mean(),inplace=True)
# defining lower and upper limits that would denote an abnormality
temp['lower'] = temp['rolling_mean']-(temp['std']*sigma)
temp['upper'] = temp['rolling_mean']+(temp['std']*sigma)
temp['anomaly'] = 0
temp.loc[(temp[values]<temp['lower'])|(temp[values]>temp['upper']),'anomaly'] = 1
del temp['resid'], temp['lower'], temp['upper'], temp['rolling_mean'], temp['std']
df = pd.concat([df,temp])
del temp
else:
temp = data.copy()
temp['rolling_mean'] = temp[values].rolling(window, min_periods=1).mean()
temp['resid'] = temp[values] - temp['rolling_mean']
## computing the rolling standard deviation on the residuals
temp['std'] = temp['resid'].rolling(window, min_periods=1).std()
temp['std'].fillna(temp['std'].mean(),inplace=True)
# defining lower and upper limits that would denote an abnormality
temp['lower'] = temp['rolling_mean']-(temp['std']*sigma)
temp['upper'] = temp['rolling_mean']+(temp['std']*sigma)
temp['anomaly'] = 0
temp.loc[(temp[values]<temp['lower'])|(temp[values]>temp['upper']),'anomaly'] = 1
del temp['resid'], temp['lower'], temp['upper'], temp['rolling_mean'], temp['std']
df = pd.concat([df,temp])
del temp
return df