在排除某些值时确定numpy数组的和

2024-05-18 06:10:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我想确定二维数组的和。但是,我想从这个总和中排除具有特定值的元素。最有效的方法是什么?

例如,在这里,我初始化一个由1组成的二维numpy数组,并用2替换其中的几个:

import numpy

data_set = numpy.ones((10, 10))

data_set[4][4] = 2
data_set[5][5] = 2
data_set[6][6] = 2

如何在排除所有2的情况下对二维数组中的元素求和?注意,使用10乘10数组,正确答案应该是97,因为我用值2替换了三个元素。

我知道我可以用嵌套for循环来实现这一点。例如:

elements = []
for idx_x in range(data_set.shape[0]):
  for idx_y in range(data_set.shape[1]):
    if data_set[idx_x][idx_y] != 2:
      elements.append(data_set[idx_x][idx_y])

data_set_sum = numpy.sum(elements)

但是在我的实际数据(这是非常大的)这是太慢了。正确的做法是什么?


Tags: 方法inimportnumpy元素fordatarange
3条回答

如何利用numpy的布尔函数呢。

在求和之前,我们只需将满足规范的所有值设置为零,这样就不会像从数组中过滤它们那样更改数组的形状。

另一个好处是,这意味着我们可以在应用过滤器后沿轴求和。

import numpy

data_set = numpy.ones((10, 10))

data_set[4][4] = 2
data_set[5][5] = 2
data_set[6][6] = 2

print "Sum", data_set.sum()

another_set = numpy.array(data_set) # Take a copy, we'll need that later

data_set[data_set == 2] = 0  # Set all the values that are 2 to zero
print "Filtered sum", data_set.sum()
print "Along axis", data_set.sum(0), data_set.sum(1)

同样,我们可以使用任何其他布尔值来设置希望从总和中排除的数据。

another_set[(another_set > 1) & (another_set < 3)] = 0
print "Another filtered sum", another_set.sum()

使用numpy的indexing with boolean arrays功能。在下面的示例中,data_set!=2求值为一个布尔数组,当元素不是2(并且具有正确的形状)时,该数组就是True。因此data_set[data_set!=2]是获取不包含某个值的数组的快捷方法。当然,布尔表达式可能更复杂。

In [1]: import numpy as np
In [2]: data_set = np.ones((10, 10))
In [4]: data_set[4,4] = 2
In [5]: data_set[5,5] = 2
In [6]: data_set[6,6] = 2
In [7]: data_set[data_set != 2].sum()
Out[7]: 97.0
In [8]: data_set != 2
Out[8]: 
array([[ True,  True,  True,  True,  True,  True,  True,  True,  True,
         True],
       [ True,  True,  True,  True,  True,  True,  True,  True,  True,
         True],
       ...
       [ True,  True,  True,  True,  True,  True,  True,  True,  True,
         True]], dtype=bool)

如果没有numpy,解决方案就不会复杂得多:

x = [1,2,3,4,5,6,7]
sum(y for y in x if y != 7)
# 21

也适用于排除值的列表:

# set is faster for resolving `in`
exl = set([1,2,3])
sum(y for y in x if y not in exl)
# 22

相关问题 更多 >