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