[英]Count number of repeated elements in a row in a numpy array
我正在尋找一種快速的方法來執行以下操作:假設我有一個數組
X = np.array([1,1,1,2,2,2,2,2,3,3,1,1,0,0,0,5])
我正在尋找連續的頻率,而不是簡單的元素頻率。 所以前 1 重復 3 次,比 2 重復 5 次,比 3 重復 2 次,等等。所以如果freq
是我的 function 比:
Y = freq(X)
Y = np.array([[1,3],[2,5],[3,2],[1,2],[0,3],[5,1]])
例如,我可以用這樣的循環來寫這個:
def freq(X):
i=0
Y=[]
while i<len(X):
el = X[i]
el_count=0
while X[i]==el:
el_count +=1
i+=1
if i==len(X):
break
Y.append(np.array([el,el_count]))
return np.array(Y)
我正在尋找一種更快更好的方法來做到這一點。 謝謝!
這是提高性能效率的一種 NumPy 方式 -
In [14]: m = np.r_[True,X[:-1]!=X[1:],True]
In [21]: counts = np.diff(np.flatnonzero(m))
In [22]: unq = X[m[:-1]]
In [23]: np.c_[unq,counts]
Out[23]:
array([[1, 3],
[2, 5],
[3, 2],
[1, 2],
[0, 3],
[5, 1]])
您可以使用itertools.groupby
來執行操作,而無需調用numpy
。
import itertools
X = [1,1,1,2,2,2,2,2,3,3,1,1,0,0,0,5]
Y = [(x, len(list(y))) for x, y in itertools.groupby(X)]
print(Y)
# [(1, 3), (2, 5), (3, 2), (1, 2), (0, 3), (5, 1)]
如果排序 output 是可以的,有numpy.unique
X = [1,1,1,2,2,2,2,2,3,3,1,1,0,0,0,5]
import numpy as np
(uniq, freq) = (np.unique(X, return_counts=True))
print(np.column_stack((uniq,freq)))
[[0 3]
[1 5]
[2 5]
[3 2]
[5 1]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.