使用每个切片的百分位数过滤多维 numpy 数组



我有一个形状为x,y,z的numpy数组,它表示x乘以y的z矩阵。我可以对每个矩阵进行切片,然后使用带有百分位数的剪辑来过滤掉异常值:

mx = array[:, :, 0]  # taking the first matrix
filtered_mx = np.clip(mx, np.percentile(mx, 1), np.percentile(mx, 99))

有没有一些有效的方法可以做同样的事情,而不必一次在切片上做?

你可以将数组传递给np.clip,因此可以在mxz维度上有不同的限制:

import numpy as np
# Create random mx
x, y, z = 10, 11, 12
mx = np.random.random((x, y, z))
# Calculate the percentiles across the x and y dimension
perc01 = np.percentile(mx, 1, axis=(0, 1), keepdims=True)
perc99 = np.percentile(mx, 99, axis=(0, 1), keepdims=True)
# Clip array with different limits across the z dimension
filtered_mx = np.clip(mx, a_min=perc01, a_max=perc99)

最新更新