查找二维数组的每一行的中值 [英] Find the median of each row of a 2 dimensional array

查看:121
本文介绍了查找二维数组的每一行的中值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到二维数组的每一行的中值.到目前为止,这是我尝试过的方法,但无法使其正常工作.任何帮助将不胜感激.

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)

推荐答案

如果您想使事情保持简单,请使用 numpy median :

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])

这篇关于查找二维数组的每一行的中值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆