仅在numpy数组的末尾查找重复项的数量 [英] Finding number of duplicates only and only at the end of a numpy array
本文介绍了仅在numpy数组的末尾查找重复项的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道如何从numpy数组中找到重复项的数量。
但是,我只需要在 numpy数组的末尾中找到重复项的数量。
请参见下面的示例:
I know how can I find the number of duplicates from a numpy array. However, I need to find the number of duplicates only at the end of the numpy array. Please see my example below:
示例输入如下:
1995
1996
1996
1997
1998
1999
1999
1999
所需的输出:
3
谢谢!
推荐答案
这是使用 np.minimum.accumulate
-
np.minimum.accumulate(a[::-1]==a[-1]).sum()
示例运行-
In [64]: a
Out[64]: array([2, 1, 9, 0, 0, 0, 2, 1, 0, 0, 0, 0, 2, 1, 0, 9, 9, 9, 9, 9])
In [73]: np.minimum.accumulate(a[::-1]==a[-1]).sum()
Out[73]: 5
另一个有 argmin
-
In [88]: (a[::-1]==a[-1]).argmin()
Out[88]: 5
对于极端情况,如果所有元素都相同,我们可能需要执行一个额外的步骤来检查 a [::-1] == a [-1]
上的所有$code>个匹配项然后返回 len(a)
。或者,如果计数为 0
(不能作为输出),我们将改为输出 len(a)
。
For a corner case, if all elements are same, we might need one extra step to check for all
matches on a[::-1]==a[-1]
and return len(a)
in that case. Or if the count is 0
, which can't be the output, we will output len(a)
instead.
这篇关于仅在numpy数组的末尾查找重复项的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文