use*_*375 1 python arrays numpy
我想在数组及其索引中找到相等的值(如果它们连续出现两次以上)。
[0, 3, 0, 1, 0, 1, 2, 1, 2, 2, 2, 2, 1, 3, 4]
Run Code Online (Sandbox Code Playgroud)
所以在这个例子中,我会发现值“2”从位置“8”开始出现“4”次。有没有内置函数可以做到这一点?
我找到了一种方法collections.Counter
collections.Counter(a)
# Counter({0: 3, 1: 4, 3: 2, 5: 1, 4: 1})
Run Code Online (Sandbox Code Playgroud)
但这不是我要找的。当然,我可以编写一个循环并比较两个值,然后对它们进行计数,但可能有更优雅的解决方案吗?
查找有条件的连续游程和游程长度
import numpy as np
arr = np.array([0, 3, 0, 1, 0, 1, 2, 1, 2, 2, 2, 2, 1, 3, 4])
res = np.ones_like(arr)
np.bitwise_xor(arr[:-1], arr[1:], out=res[1:]) # set equal, consecutive elements to 0
# use this for np.floats instead
# arr = np.array([0, 3, 0, 1, 0, 1, 2, 1, 2.4, 2.4, 2.4, 2, 1, 3, 4, 4, 4, 5])
# res = np.hstack([True, ~np.isclose(arr[:-1], arr[1:])])
idxs = np.flatnonzero(res) # get indices of non zero elements
values = arr[idxs]
counts = np.diff(idxs, append=len(arr)) # difference between consecutive indices are the length
cond = counts > 2
values[cond], counts[cond], idxs[cond]
Run Code Online (Sandbox Code Playgroud)
输出
(array([2]), array([4]), array([8]))
# (array([2.4, 4. ]), array([3, 3]), array([ 8, 14]))
Run Code Online (Sandbox Code Playgroud)