Skip to content

Instantly share code, notes, and snippets.

@govorunov
Last active June 29, 2021 06:05
Show Gist options
  • Save govorunov/96309539e12030aef42d9a1fe37b90f6 to your computer and use it in GitHub Desktop.
Save govorunov/96309539e12030aef42d9a1fe37b90f6 to your computer and use it in GitHub Desktop.
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