Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Multidimensional Arrays - most efficient way to count number of non-zero entries

Hi there on a Saturday Fun Night,

I am getting around in python and I am quite enjoying it.

Assume I have a python array:

x = [1, 0, 0, 1, 3]

What is the fastest way to count all non zero elements in the list (ans: 3) ? Also I would like to do it without for loops if possible - the most succint and terse manner possibe, say something conceptually like

[counter += 1 for y in x if y > 0]

Now - my real problem is that I have a multi dimensional array and what I really want to avoid is doing the following:

for p in range(BINS):
    for q in range(BINS):
        for r in range(BINS):
            if (mat3D[p][q][r] > 0): some_feature_set_count += 1

From the little python I have seen, my gut feeling is that there is a really clean syntax (and efficient) way how to do this.

Ideas, anyone?

like image 614
MalteseUnderdog Avatar asked Nov 27 '10 23:11

MalteseUnderdog


People also ask

How do you count nonzero elements in an array Python?

count_nonzero() function counts the number of non-zero values in the array arr. Parameters : arr : [array_like] The array for which to count non-zeros. axis : [int or tuple, optional] Axis or tuple of axes along which to count non-zeros.

How do you count the number of non zeros in a NumPy array?

The Numpy count_nonzero() function is used to give the count of the nonzero elements present in the multidimensional array. With the help of this function, we can find the count of the elements in the multidimensional array which are not zero. This function has 3 parameters as arr, axis and, keepdims.

Which NumPy functionality is about this fast and space efficient multidimensional array providing?

ndarray , a fast and space-efficient multidimensional array providing vectorized arithmetic operations and sophisticated broadcasting capabilities.

How do you count the number of zeros in an array in Python?

To count all the zeros in an array, simply use the np. count_nonzero() function checking for zeros. It returns the count of elements inside the array satisfying the condition (in this case, if it's zero or not).


2 Answers

For the single-dimensional case:

sum(1 for i in x if i)

For the multi-dimensional case, you can either nest:

sum(sum(1 for i in row if i) for row in rows)

or do it all within the one construct:

sum(1 for row in rows
      for i in row if i)
like image 156
Marcelo Cantos Avatar answered Nov 14 '22 21:11

Marcelo Cantos


If you are using numpy as suggested by the fact that you're using multi-dimensional arrays in Python, the following is similar to @Marcelo's answer, but a tad cleaner:

>>> a = numpy.array([[1,2,3,0],[0,4,2,0]])
>>> sum(1 for i in a.flat if i)
5
>>>
like image 35
Chinmay Kanchi Avatar answered Nov 14 '22 23:11

Chinmay Kanchi