【问题标题】:How can I compute things, but omit certain numpy elements?我如何计算事物,但省略某些 numpy 元素?
【发布时间】:2023-03-17 18:43:01
【问题描述】:

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

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

【问题讨论】:

标签: python arrays numpy


【解决方案1】:

根据您的 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 &lt;= x) &amp; (x &lt;= x_max)]
  2. x = x[np.where((x_min &lt;= x) &amp; (x &lt;= x_max))]
  3. x = np.delete(x, np.where(~(x_min &lt;= x) | ~(x &lt;= x_max)))

分配后,x = [2 3 4],那些满足边界条件的元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    • 2017-06-28
    • 2011-01-22
    • 1970-01-01
    相关资源
    最近更新 更多