Advertisement
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
- try:
- tmpMonthArray[each[whichElementIsKey]-startKey].append(each[whichElementIsValue]) #be careful with 'each[0]-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)+"'")
- raise
- i=1
- resultArray=[]
- for each in tmpMonthArray: # cycle through reconfigured array to calculate median by key array
- resultArray.append([i,np.median(each)])
- i+=1
- 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]]
- i=1
- # the second array2 is synthetically generated in next loop and it will consist half the values of array1, keeping the same keys
- array2=[]
- for each in array1:
- tmp=[i,each[1]/2]
- array2.append(tmp)
- i+=1
- #lets check them
- print "array 1", array1
- print ""
- print "array 2", array2
- print""
- #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.
- wrapperArray=[]
- wrapperArray.append(array1)
- wrapperArray.append(array2)
- #check out the configuration of such wrapper array. simple, huh?
- print "wrapper array", wrapperArray
- print""
- 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""
- print "calculated medianas by key with default whichElementIsValue=1, whichElementIsKey=0, startKey=1", monthlyMediana(wrapperArray,length)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement