Count Nan-Values per Column in an ndarray

Question:

Problem:
I have a ndarray (2000,7) and I want to count the numbers of Nan’s per column and save it in an ndarray

Tried:

number_nan_in_arr = np.count_nonzero(np.isnan(arr))

But this count the total number of nan’s over all columns

Solution: ?

Asked By: SebastianHeeg

||

Answers:

You can add axis=0 to count null per column:

number_nan_in_arr = np.count_nonzero(np.isnan(arr), axis=0)

Example:

import numpy as np 

a = np.array([[0, np.nan, 7, 0],
              [3, 0, 2, np.nan]])
np.count_nonzero(np.isnan(a), axis=0)

Output:

array([0, 1, 0, 1], dtype=int64)
Answered By: Hamzah

Simply sum the True values:

number_nan_in_arr = np.isnan(arr).sum(0)
Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.