如果它們連續出現超過 2 次,我想在陣列及其索引中找到相等的值。
[0, 3, 0, 1, 0, 1, 2, 1, 2, 2, 2, 2, 1, 3, 4]
所以在這個例子中,我會發現值“2”出現了“4”次,從位置“8”開始。是否有任何內置功能可以做到這一點?
我找到了一種方法collections.Counter
collections.Counter(a)
# Counter({0: 3, 1: 4, 3: 2, 5: 1, 4: 1})
但這不是我要找的。當然我可以撰寫一個回圈并比較兩個值然后計算它們,但可能有更優雅的解決方案嗎?
uj5u.com熱心網友回復:
查找有條件的連續運行和運行長度
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]
輸出
(array([2]), array([4]), array([8]))
# (array([2.4, 4. ]), array([3, 3]), array([ 8, 14]))
uj5u.com熱心網友回復:
_, i, c = np.unique(np.r_[[0], ~np.isclose(arr[:-1], arr[1:])].cumsum(),
return_index = 1,
return_counts = 1)
for index, count in zip(i, c):
if count > 1:
print([arr[index], count, index])
Out[]: [2, 4, 8]
一種更緊湊的方法,適用于所有輸入型別。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/456448.html
下一篇:異步函式后陣列未排序
