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
  • @SeanPianka not a duplicate, the OP is asking about numpy arrays – juanpa.arrivillaga Nov 08 '18 at 23:02
  • @SeanPianka: Not a duplicate of that question, since lists and arrays behave differently. Might be a duplicate of some other question, though. – user2357112 Nov 08 '18 at 23:03
  • It is a duplicate of this question: https://stackoverflow.com/questions/28663856/how-to-count-the-occurrence-of-certain-item-in-an-ndarray-in-python – Sean Pianka Nov 08 '18 at 23:04
  • 1
    @wsun88: `a = [[1, 2, 3], [2, 3, 4], [3, 4, 5], [1, 2, 3]]` is not what a NumPy array looks like. That line would produce a list. The differences between lists and arrays matter; be aware of which type you're using. – user2357112 Nov 08 '18 at 23:04
  • @user2357112 I didn't really know how to represent numpy arrays, so I just represented it as a list – wsun88 Nov 08 '18 at 23:16

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
  • 49,704
  • 8
  • 81
  • 106
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
  • 61,499
  • 6
  • 49
  • 76