Last active
June 29, 2021 06:05
-
-
Save govorunov/96309539e12030aef42d9a1fe37b90f6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
def np_z_trim(x, threshold=10, axis=0): | |
""" Replace outliers in numpy ndarray along axis with min or max values | |
within the threshold along this axis, whichever is closer.""" | |
mean = np.mean(x, axis=axis, keepdims=True) | |
std = np.std(x, axis=axis, keepdims=True) | |
masked = np.where(np.abs(x - mean) < threshold * std, x, np.nan) | |
min = np.nanmin(masked, axis=axis, keepdims=True) | |
max = np.nanmax(masked, axis=axis, keepdims=True) | |
repl = np.where(np.abs(x - max) < np.abs(x - min), max, min) | |
return np.where(np.isnan(masked), repl, masked) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment