Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting occurrences of columns in numpy array

Tags:

python

numpy

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?

like image 340
Christopher Avatar asked Dec 12 '15 00:12

Christopher


People also ask

How do you count how many times something appears in an array in Python?

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.

Is there a count function in NumPy?

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.

How do you count elements in Ndarray?

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.


1 Answers

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})
like image 94
eph Avatar answered Sep 21 '22 01:09

eph