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?
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]
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)
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?
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]
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)