我如何计算事物,但省略某些 numpy 元素



我有一组数据,我想对其进行标准化。但是,在集合中,有一些我不想使用的数字(异常值)。

因此,更一般地说,有没有办法在 numpy 中进行数组计算并省略某些数组元素

根据 numpy 数组的实现方式,您可以使用如下所示的条件操作:

import numpy as np
# Instantiates a sample array.
x = np.array([1, 2, 3, 4, 5])
# Sets the boundary conditions of the operation.
x_min = 2
x_max = 4
# Performs an operation on elements satisfying the boundary conditions.
x[(x_min <= x) & (x <= x_max)] += 10

在这种情况下,在条件操作之前,x = [1, 2, 3, 4, 5] .但是,在条件操作之后,x = [1, 12, 13, 14, 5] .也就是说,它只在满足边界条件的那些元素上运行。

您也可以使用 numpy where() 函数来完成相同的操作:

x[np.where((x_min <= x) & (x <= x_max))] += 10

但是,如果要从数组中完全省略不需要的值,则可以使用以下任一值:

  1. x = x[(x_min <= x) & (x <= x_max)]
  2. x = x[np.where((x_min <= x) & (x <= x_max))]
  3. x = np.delete(x, np.where(~(x_min <= x) | ~(x <= x_max)))

对于赋值后,x = [2 3 4],那些满足边界条件的元素。

最新更新