Aravindh Vasu
Aravindh Vasu

Reputation: 158

Counting the occurence of numpy.array object in a list of numpy.array objects

If I have a list:

a = [np.array([1,1,1]), np.array([1,1,1]), np.array([1,1,1])]

How to do something like, a.count(np.array([1,1,1])? This throws:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Is there a function similar to .count()?

Upvotes: 3

Views: 74

Answers (2)

Dima Chubarov
Dima Chubarov

Reputation: 17159

Or map np.array_equal and apply count to the result

map(lambda x: np.array_equal(np.array([1,1,1]),x), a).count(True)

Upvotes: 1

Austin
Austin

Reputation: 26039

You can use np.array_equal with sum on generator:

>>> sum(np.array_equal(x, [1,1,1]) for x in a)
3

Upvotes: 1

Related Questions