Given a 2 x d dimensional numpy array M, I want to count the number of occurences of each column of M. That is, I'm looking for a general version of bincount
.
What I tried so far: (1) Converted columns to tuples (2) Hashed tuples (via hash
) to natural numbers (3) used numpy.bincount
.
This seems rather clumsy. Is anybody aware of a more elegant and efficient way?
The easiest way to count the number of occurrences in a Python list of a given item is to use the Python . count() method. The method is applied to a given list and takes a single argument. The argument passed into the method is counted and the number of occurrences of that item in the list is returned.
NumPy: count() function count() function returns an array with the number of non-overlapping occurrences of substring sub in the range [start, end]. Input an array_like of string or unicode. The substring to search for.
Count the number of elements satisfying the condition for the entire ndarray. The comparison operation of ndarray returns ndarray with bool ( True , False ). Using np. count_nonzero() gives the number of True , i.e., the number of elements that satisfy the condition.
You can use collections.Counter
:
>>> import numpy as np
>>> a = np.array([[ 0, 1, 2, 4, 5, 1, 2, 3],
... [ 4, 5, 6, 8, 9, 5, 6, 7],
... [ 8, 9, 10, 12, 13, 9, 10, 11]])
>>> from collections import Counter
>>> Counter(map(tuple, a.T))
Counter({(2, 6, 10): 2, (1, 5, 9): 2, (4, 8, 12): 1, (5, 9, 13): 1, (3, 7, 11):
1, (0, 4, 8): 1})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With