我正在使用不同的标准偏差标准对 pandas Series 对象进行两次通过的异常值检查。但是,我为此使用了两个循环,并且运行速度非常慢。我想知道是否有任何熊猫“技巧”来加快这一步。
这是我正在使用的代码(警告非常丑陋的代码!):
def find_outlier(point, window, n):
return np.abs(point - nanmean(window)) >= n * nanstd(window)
def despike(self, std1=2, std2=20, block=100, keep=0):
res = self.values.copy()
# First run with std1:
for k, point in enumerate(res):
if k <= block:
window = res[k:k + block]
elif k >= len(res) - block:
window = res[k - block:k]
else:
window = res[k - block:k + block]
window = window[~np.isnan(window)]
if np.abs(point - window.mean()) >= std1 * window.std():
res[k] = np.NaN
# Second run with std2:
for k, point in enumerate(res):
if k <= block:
window = res[k:k + block]
elif k >= len(res) - block:
window = res[k - block:k]
else:
window = res[k - block:k + block]
window = window[~np.isnan(window)]
if np.abs(point - window.mean()) >= std2 * window.std():
res[k] = np.NaN
return Series(res, index=self.index, name=self.name)