2015-11-11 80 views
2

我正在嘗試查找二維數組的每一行的中位數。這是我到目前爲止所嘗試的,但我無法得到它的工作。任何幫助將不勝感激。查找二維數組的每一行的中位數

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) 

回答

0

首先,明顯的變量命名錯誤:Matrix未定義。你可能意思是list,或者你的意思是將函數參數命名爲Matrix。 Btw list不是一個好的變量名,因爲Python數據類型爲list。另外Matrix也不是一個好名字,因爲最好使用變量名小寫。另外,srtd未定義。

一旦你糾正了命名錯誤,那麼下一個問題是sorted(xyz)不會修改xyz,但會返回xyz的排序副本。所以你需要把它分配給某些東西。那麼,請不要將它分配回Matrix[lineindex],因爲那樣這個函數將會有改變傳遞給它的輸入矩陣的不良副作用。

0

這應該會幫助你一點。正如@Rishi所說,有很多變量名稱問題。

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

如果你想使事情變得簡單,使用numpymedian

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