Use count_nonzero to count non-zero (e.g. not False) values:
>>> np.size(a) - np.count_nonzero(a)
2
The clearer is surely to ask exactly what is needed, but that doesn't mean it is the most efficient:
Using %%timeit in jupyter with python 2.7 on the proposed answers gives a clear winner:
seq = [[True, True, False, True, False, False, False] * 10 for _ in range(100)]
a = np.array(seq)
np.size(a) - np.count_nonzero(a) 1000000 loops, best of 3: 1.34 µs per loop - Antti Haapala
(~a).sum() 100000 loops, best of 3: 18.5 µs per loop - Paul H
np.size(a) - np.sum(a) 10000 loops, best of 3: 18.8 µs per loop - OP
len(a[a == False]) 10000 loops, best of 3: 52.4 µs per loop
len(np.where(a==False)) 10000 loops, best of 3: 77 µs per loop - Forzaa
.
The clear winner is Antti Haapala, by an order of magnitude, with np.size(a) - np.count_nonzero(a)
len(np.where(a==False)) seems to be penalized by the nested structure of the array; the same benchmark on a 1 D array gives 10000 loops, best of 3: 27 µs per loop
np.count_nonzero(~np.isnan(data))
~ inverts the boolean matrix returned from np.isnan.
np.count_nonzero counts values that is not 0\false. .sum should give the same result. But maybe more clearly to use count_nonzero
Testing speed:
In [23]: data = np.random.random((10000,10000))
In [24]: data[[np.random.random_integers(0,10000, 100)],:][:, [np.random.random_integers(0,99, 100)]] = np.nan
In [25]: %timeit data.size - np.count_nonzero(np.isnan(data))
1 loops, best of 3: 309 ms per loop
In [26]: %timeit np.count_nonzero(~np.isnan(data))
1 loops, best of 3: 345 ms per loop
In [27]: %timeit data.size - np.isnan(data).sum()
1 loops, best of 3: 339 ms per loop
data.size - np.count_nonzero(np.isnan(data)) seems to barely be the fastest here. other data might give different relative speed results.
Quick-to-write alternative
Even though is not the fastest choice, if performance is not an issue you can use:
sum(~np.isnan(data)).
Performance:
In [7]: %timeit data.size - np.count_nonzero(np.isnan(data))
10 loops, best of 3: 67.5 ms per loop
In [8]: %timeit sum(~np.isnan(data))
10 loops, best of 3: 154 ms per loop
In [9]: %timeit np.sum(~np.isnan(data))
10 loops, best of 3: 140 ms per loop
Assuming you mean total number of nonzero elements (and not total number of nonzero rows):
In [12]: a = np.random.randint(0, 3, size=(100,100))
In [13]: timeit len(a.nonzero()[0])
1000 loops, best of 3: 306 us per loop
In [14]: timeit (a != 0).sum()
10000 loops, best of 3: 46 us per loop
or even better:
In [22]: timeit np.count_nonzero(a)
10000 loops, best of 3: 39 us per loop
This last one, count_nonzero, seems to behave well when the array is small, too, whereas the sum trick not so much:
In [33]: a = np.random.randint(0, 3, size=(10,10))
In [34]: timeit len(a.nonzero()[0])
100000 loops, best of 3: 6.18 us per loop
In [35]: timeit (a != 0).sum()
100000 loops, best of 3: 13.5 us per loop
In [36]: timeit np.count_nonzero(a)
1000000 loops, best of 3: 686 ns per loop
len(np.nonzero(array)[0]) ?
np.nonzeroreturns a tuple of indices, whose length is equal to the number of dimensions in the initial array- we get just the indices along the first dimension with
[0] - compute its length with
len
You may also consider, well, counting the nonzero values:
import numba as nb
@nb.njit()
def count_loop(a):
s = 0
for i in a:
if i != 0:
s += 1
return s
I know it seems wrong, but bear with me:
import numpy as np
import numba as nb
@nb.njit()
def count_loop(a):
s = 0
for i in a:
if i != 0:
s += 1
return s
@nb.njit()
def count_len_nonzero(a):
return len(np.nonzero(a)[0])
@nb.njit()
def count_sum_neq_zero(a):
return (a != 0).sum()
np.random.seed(100)
a = np.random.randint(0, 3, 1000000000, dtype=np.uint8)
c = np.count_nonzero(a)
assert count_len_nonzero(a) == c
assert count_sum_neq_zero(a) == c
assert count_loop(a) == c
%timeit count_len_nonzero(a)
# 5.94 s ± 141 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit count_sum_neq_zero(a)
# 848 ms ± 80.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit count_loop(a)
# 189 ms ± 4.41 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
It is in fact faster than np.count_nonzero, which can get quite slow for some reason:
%timeit np.count_nonzero(a)
# 4.36 s ± 69.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In case you need it really fast for large arrays you could even use numbas prange to process the count in parallel (for small arrays it will be slower due to the parallel-processing overhead).
import numpy as np
from numba import njit, prange
@njit(parallel=True)
def parallel_nonzero_count(arr):
flattened = arr.ravel()
sum_ = 0
for i in prange(flattened.size):
sum_ += flattened[i] != 0
return sum_
Note that when you use numba you normally want to write out your loops because that's what numba is really very good at optimizing.
I actually timed it against the other solutions mentioned here (using my Python module simple_benchmark):

Code to reproduce:
import numpy as np
from numba import njit, prange
@njit
def n_nonzero(a):
return a[a != 0].size
@njit
def count_non_zero(np_arr):
return len(np.nonzero(np_arr)[0])
@njit()
def methodB(a):
return (a!=0).sum()
@njit(parallel=True)
def parallel_nonzero_count(arr):
flattened = arr.ravel()
sum_ = 0
for i in prange(flattened.size):
sum_ += flattened[i] != 0
return sum_
@njit()
def count_loop(a):
s = 0
for i in a:
if i != 0:
s += 1
return s
from simple_benchmark import benchmark
args = {}
for exp in range(2, 20):
size = 2**exp
arr = np.random.random(size)
arr[arr < 0.3] = 0.0
args[size] = arr
b = benchmark(
funcs=(n_nonzero, count_non_zero, methodB, np.count_nonzero, parallel_nonzero_count, count_loop),
arguments=args,
argument_name='array size',
warmups=(n_nonzero, count_non_zero, methodB, np.count_nonzero, parallel_nonzero_count, count_loop)
)
import numpy as np
a = np.array([[1, 0, 1],
[2, 3, 4],
[0, 0, 7]])
columns = (a != 0).sum(0)
rows = (a != 0).sum(1)
The variable (a != 0) is an array of the same shape as original a and it contains True for all non-zero elements.
The .sum(x) function sums the elements over the axis x. Sum of True/False elements is the number of True elements.
The variables columns and rows contain the number of non-zero (element != 0) values in each column/row of your original array:
columns = np.array([2, 1, 3])
rows = np.array([2, 3, 1])
EDIT: The whole code could look like this (with a few simplifications in your original code):
ANOVAInputMatrixValuesArray = zeros([len(TestIDs), 9], float)
for j, TestID in enumerate(TestIDs):
ReadOrWrite = 'Read'
fileName = inputFileName
directory = GetCurrentDirectory(arguments that return correct directory)
# use directory or filename to get the CSV file?
with open(directory, 'r') as csvfile:
ANOVAInputMatrixValuesArray[j,:] = loadtxt(csvfile, comments='TestId', delimiter=';', usecols=(2,))[:9]
nonZeroCols = (ANOVAInputMatrixValuesArray != 0).sum(0)
nonZeroRows = (ANOVAInputMatrixValuesArray != 0).sum(1)
EDIT 2:
To get the mean value of all columns/rows, use the following:
colMean = a.sum(0) / (a != 0).sum(0)
rowMean = a.sum(1) / (a != 0).sum(1)
What do you want to do if there are no non-zero elements in a column/row? Then we can adapt the code to solve such a problem.
A fast way to count nonzero elements per row in a scipy sparse matrix m is:
np.diff(m.tocsr().indptr)
The indptr attribute of a CSR matrix indicates the indices within the data corresponding to the boundaries between rows. So calculating the difference between each entry will provide the number of non-zero elements in each row.
Similarly, for the number of nonzero elements in each column, use:
np.diff(m.tocsc().indptr)
If the data is already in the appropriate form, these will run in O(m.shape[0]) and O(m.shape[1]) respectively, rather than O(m.getnnz()) in Marat and Finn's solutions.
If you need both row and column nozero counts, and, say, m is already a CSR, you might use:
row_nonzeros = np.diff(m.indptr)
col_nonzeros = np.bincount(m.indices)
which is not asymptotically faster than first converting to CSC (which is O(m.getnnz())) to get col_nonzeros, but is faster because of implementation details.