I have a numpy array like this:
foo_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]
I want to replace all zeros with the median value of the entire array (where zero values should not be included in the calculation of the median)
So far this has been going on:
foo_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) foo = np.sort(foo) print "foo sorted:",foo #foo sorted: [ 0 0 0 0 0 3 5 8 14 15 16 17 18 19 21 26 27 29 29 31 38 38 40 49 55] nonzero_values = foo[0::] > 0 nz_values = foo[nonzero_values] print "nonzero_values?:",nz_values #nonzero_values?: [ 3 5 8 14 15 16 17 18 19 21 26 27 29 29 31 38 38 40 49 55] size = np.size(nz_values) middle = size / 2 print "median is:",nz_values[middle] #median is: 26
Is there a smart way to achieve this using numpy syntax?
thanks