How to count the number of 1D arrays in a 2D array (Python)?

669 views python
7

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)

answered question

2 Answers

3

Use the count method of the list

>>> a.count([1,2,3])
2

posted this
4

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

posted this

Have an answer?

JD

Please login first before posting an answer.