replace zeroes in numpy array with the median value replace zeroes in numpy array with the median value python python

replace zeroes in numpy array with the median value


This solution takes advantage of numpy.median:

import numpy as npfoo_array = [38,26,14,55,31,0,15,8,0,0,0,18,40,27,3,19,0,49,29,21,5,38,29,17,16]foo = np.array(foo_array)# Compute the median of the non-zero elementsm = np.median(foo[foo > 0])# Assign the median to the zero elements foo[foo == 0] = m

Just a note of caution, the median for your array (with no zeroes) is 23.5 but as written this sticks in 23.


foo2 = foo[:]foo2[foo2 == 0] = nz_values[middle]

Instead of foo2, you could just update foo if you want. Numpy's smart array syntax can combine a few lines of the code you made. For example, instead of,

nonzero_values = foo[0::] > 0nz_values = foo[nonzero_values]

You can just do

nz_values = foo[foo > 0]

You can find out more about "fancy indexing" in the documentation.