Find median or any statistic parameter in loop by array key
a guest Nov 14th, 2012 9 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
- import numpy as np
- def monthlyMediana(array, length, whichElementIsValue=1, whichElementIsKey=0, startKey=1):
- tmpMonthArray=[*length for x in xrange(length)] # how long the array is? (if calculate over months, there are 12 month and then value is 12)
- for liste in array: # cycle to reconfiguring array "by key"
- for each in liste: # inner cycle to get out values from array
- tmpMonthArray[each[whichElementIsKey]-startKey].append(each[whichElementIsValue]) #be careful with 'each-startKey' By default the first element = 1, but its index in tmpArray is 0. So to correct it, subtracting helps to get correct index.
- except Exception:
- print ("Check input array in function 'monthlyMediana'! There is no value in defined element '" + str(whichElementIsValue)+"'")
- for each in tmpMonthArray: # cycle through reconfigured array to calculate median by key array
- return resultArray
- # testing function calculating median from two arrays. the first one-
- # array1 is manually created, by hand, consists of pairs - key and value
- array1=[[1, 83.08781741696035], [2, 83.00913411194273], [3, 82.87611049475012], [4, 81.9209957077651], [5, 83.29382676081318], [6, 86.43752414116936], [7, 90.28708527096674], [8, 85.4778304673852], [9, 81.50339901314508], [10, 82.86330480401524], [11, 81.2255531150904], [12, 81.61939222634093]]
- # the second array2 is synthetically generated in next loop and it will consist half the values of array1, keeping the same keys
- for each in array1:
- #lets check them
- print "array 1", array1
- print ""
- print "array 2", array2
- #now we need to combine both arrays into array, which can be given to monthlyMediana function.
- # it is like a wrapeer, wraps both small arrays.
- #check out the configuration of such wrapper array. simple, huh?
- print "wrapper array", wrapperArray
- length=len(array1) #how many keys we have?
- print "how many keys we have?", length
- print ""
- print "calculated medianas by key", monthlyMediana(wrapperArray,length,1,0,1)
- print "calculated medianas by key with default whichElementIsValue=1, whichElementIsKey=0, startKey=1", monthlyMediana(wrapperArray,length)
RAW Paste Data