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)

5
  • @SeanPianka not a duplicate, the OP is asking about numpy arrays Commented Nov 8, 2018 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. Commented Nov 8, 2018 at 23:03
  • It is a duplicate of this question: stackoverflow.com/questions/28663856/… Commented Nov 8, 2018 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. Commented Nov 8, 2018 at 23:04
  • @user2357112 I didn't really know how to represent numpy arrays, so I just represented it as a list Commented Nov 8, 2018 at 23:16

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.