3

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?

chrslg
  • 9,023
  • 5
  • 17
  • 31
islam abdelmoumen
  • 662
  • 1
  • 3
  • 9

2 Answers2

4

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]

Alex P
  • 1,105
  • 6
  • 18
1

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)
Ajay K
  • 183
  • 11