0

If I have a numpy 2D array, say:

a = [[1, 2, 3], [2, 3, 4], [3, 4, 5], [1, 2, 3]]

How do I count the number of instances of [1, 2, 3] in a? (The answer I'm looking for is 2 in this case)

wsun88
  • 29
  • 2

2 Answers2

2

Since you said it's a numpy array, rather than a list, you can do something like:

>>> a = np.array([[1, 2, 3], [2, 3, 4], [3, 4, 5], [1, 2, 3]])
>>> sum((a == [1,2,3]).all(1))
2

(a == [1,2,3]).all(1) gives you a boolean array or where all the values in the row match [1,2,3]: array([ True, False, False, True], dtype=bool), and the sum of that is the count of all True values in there

sacuL
  • 42,057
  • 8
  • 58
  • 83
1

If you want the counts of all the arrays you could use unique:

import numpy as np

a = np.array([[1, 2, 3], [2, 3, 4], [3, 4, 5], [1, 2, 3]])
uniques, counts = np.unique(a, return_counts=True, axis=0)
print([(unique, count) for unique, count in zip(uniques, counts)])

Output

[(array([1, 2, 3]), 2), (array([2, 3, 4]), 1), (array([3, 4, 5]), 1)]
Dani Mesejo
  • 43,691
  • 6
  • 29
  • 53