Skip to content Skip to sidebar Skip to footer

Find The Median Of Each Row Of A 2 Dimensional Array

I am trying to find the median of each row of a 2 dimensional array. This is what I have tried so far but I cannot get it to work. Any help would be greatly appreciated. def median

Solution 1:

If you want to keep things simple, use numpy's median:

matrix = numpy.array(zip(range(10), [x+1for x inrange(10)])).T
# array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],#        [ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10]])
np.median(matrix, axis=1) # array([ 4.5,  5.5])

Solution 2:

First, the obvious variable naming errors: Matrix is not defined. You probably meant list, or you meant to name the function argument as Matrix. Btw list is not a good variable name to have, as there is Python data type list. Also Matrix isn't a good name either, as it's good practice to have variable names lowercase. Also, srtd is not defined.

Once you correct the naming errors, then the next problem is sorted(xyz) does not modify xyz, but returns a sorted copy of xyz. So you need to assign it to something. Well, don't assign it back to Matrix[lineindex], because then the function will have the undesirable side effect of changing the input matrix passed to it.

Solution 3:

This should help you out a bit. As @Rishi said, there were a lot of variable name issues.

defmedian_rows(matrix):
    for line in matrix:  # line is each row of the matrix
        sorted_line = sorted(line)  # have to set the sorted line to a variable
        mid_point = len(sorted_line) / 2# only need to do one, because we know the upper index will always be the one after the midpointiflen(line) % 2 == 0:
            # have to take avg of middle two
            median = (sorted_line[mid_point] + sorted_line[mid_point + 1]) / 2.0print"The median is %f" % median  
        else:
            median = line[mid_point]
            print"The median is %d" % median

matrix = [[1,2,3,5],[1,2,3,7]]

median_rows(matrix)

Post a Comment for "Find The Median Of Each Row Of A 2 Dimensional Array"