I'm looking for a quick way to do the following: Say I have an array
X = np.array([1,1,1,2,2,2,2,2,3,3,1,1,0,0,0,5])
Instead of a simple frequency of elements I'm looking for the frequency in a row. So first 1 repeats 3 times, than 2 5 times, than 3 2 times , etc. So if freq
is my function than:
Y = freq(X)
Y = np.array([[1,3],[2,5],[3,2],[1,2],[0,3],[5,1]])
For example, I can write this with loops like this:
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)
I'm looking for a faster and nicer way to do this. Thanks!