计算特定值的出现并同时将其删除 [英] Count the occurrences of a specific value and remove them at the same time
问题描述
我想计算一个特定值(以我的情况为-1
)在numpy数组中的出现次数,并同时将其删除.
I want to count the occurrences of a specific value (in my case -1
) in a numpy array and delete them at the same time.
我可以这样做,所以这是我所做的:
I could do that so here is what I've done:
a = np.array([1, 2, 0, -1, 3, -1, -1])
b = a[a==-1]
a = np.delete(a, np.where(a==-1))
print("a -> ", a) # a -> [1 2 0 3]
print("b -> ", b) # b -> 3
还有其他更优化的方法吗?
Is there any more optimised way to do it ?
推荐答案
首先,列出就地计数和删除操作:
First, a list in-place count and delete operation:
In [100]: al=a.tolist(); cnt=0
In [101]: for i in range(len(a)-1,-1,-1):
...: if al[i]==-1:
...: del al[i]
...: cnt += 1
In [102]: al
Out[102]: [1, 2, 0, 3]
In [103]: cnt
Out[103]: 3
它可以就地运行,但是必须从头开始工作.列表理解替代方法创建了一个新列表,但通常更易于编写和阅读.
It operates in place, but has to work from the end. The list comprehension alternative makes a new list, but often is easier to write and read.
最干净的数组操作使用布尔掩码.
The cleanest array operation uses a boolean mask.
In [104]: idx = a==-1
In [105]: idx
Out[105]: array([False, False, False, True, False, True, True], dtype=bool)
In [106]: np.sum(idx) # or np.count_nonzero(idx)
Out[106]: 3
In [107]: a[~idx]
Out[107]: array([1, 2, 0, 3])
您必须以一种或其他方式标识与目标匹配的所有元素.计数是微不足道的操作.遮罩也很容易.
You have to identify, in one way or other, all elements that match the target. The count is a trivial operation. Masking is also easy.
np.delete
必须被告知要删除哪些项目;然后以一种或其他方式构造一个新数组,其中包含除已删除"数组之外的所有数组.由于它的通用性,它几乎总是比像这种掩盖这样的直接动作要慢.
np.delete
has to be told which items to delete; and in one way or other constructs a new array that contains all but the 'deleted' ones. Because of its generality it will almost always be slower than a direct action like this masking.
np.where
(又名np.nonzeros
)使用count_nonzero
来确定它将返回多少个值.
np.where
(aka np.nonzeros
) uses count_nonzero
to determine how many values it will return.
所以我提议的动作与您正在执行的动作相同,但是采用的是更直接的方式.
So I'm proposing the same actions as you are doing, but in a little more direct way.
这篇关于计算特定值的出现并同时将其删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!