count the arrays in a large array

Question:

I wrote the following code but when the rows are large it is slow

import numpy as np

array = np.array([
                   [1,2],[1,2],[2,3],
                   [1,2],[2,3],[5,2]])
d={}
for l in array:
    t = tuple(l)
    if t in d:
        d[t]+=1
    else:
        d[t]=1
print(d)

result:

`{(1, 2): 3, (2, 3): 2, (5, 2): 1}`

Is there a faster way to do this?

Asked By: islam abdelmoumen

||

Answers:

Use np.unique

elements, counts = np.unique(array, axis=0, return_counts=True)

In your case, elements will be

[[1, 2],
 [2, 3],
 [5, 2]]

and counts will be
[3, 2, 1]

Answered By: Alex P

Without numpy library be like

final_count={}
for lst in [list(x) for x in set(tuple(x) for x in array)]:
     final_count[tuple(lst)]=array.count(lst)
Answered By: Ajay K
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.