How to count the frequency of certain item in numpy array with Python

2 Answers

0 votes
import numpy as np
 
arr = np.array([1,1,1,3,3,4,5,7,1,1,2,2,2,2,1,2,3,3])
 
unique, counts = np.unique(arr, return_counts=True)
 
result = np.asarray((unique, counts)).T
 
print(result)
 
print(result[2][0], "=", result[2][1], "times")
 
 
 
 
'''
run:
 
[[1 6]
 [2 5]
 [3 4]
 [4 1]
 [5 1]
 [7 1]]
3 = 4 times
 
'''

 



answered Mar 21, 2023 by avibootz
0 votes
import numpy as np
import collections 
 
arr = np.array([1,1,1,3,3,4,5,7,1,1,2,2,2,2,1,2,3,3])

result = collections.Counter(arr)

print(result)

print("3 =", result[3], "times")
 
 
 
 
'''
run:
 
Counter({1: 6, 2: 5, 3: 4, 4: 1, 5: 1, 7: 1})
3 = 4 times

'''

 



answered Mar 21, 2023 by avibootz

Related questions

...