Find the median of each row of a 2 dimensional array

瘦欲@ 提交于 2019-12-13 16:09:45

问题


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_rows(list):            
    for lineindex in range(len(Matrix)):
        sorted(Matrix[lineindex])

        mid_upper = ((len(Matrix[lineindex]))/2
        mid_lower = ((len(Matrix[lineindex])+1)/2
        if len(Matrix[lineindex])%2 == 0:
            #have to take avg of middle two
            median = (Matrix[mid_lower] + Matrix[mid_upper])/2.0
            print "The median is %f" %median
       else:
            median = srtd[mid]  
            print "The median is %d" %median


median_rows(Matrix)

回答1:


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

matrix = numpy.array(zip(range(10), [x+1 for x in range(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])



回答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.




回答3:


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

def median_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 midpoint
        if len(line) % 2 == 0:
            # have to take avg of middle two
            median = (sorted_line[mid_point] + sorted_line[mid_point + 1]) / 2.0
            print "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)


来源:https://stackoverflow.com/questions/33658580/find-the-median-of-each-row-of-a-2-dimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!