python - Mean function given a list of graphs -


i need function that, given list of graphs, builds new graph in each abscissa ordinate average of ordinate of several graphs supplied.

the data each graph pair of lists of numbers, first of abscissa , ordinate second.

the function should assume graphs have same abscissa lists.

for example:

abscissa = range(1, 4) graphs = [     (abscissa, [1, 2, 3]),     (abscissa, [4, 5, 6]),     (abscissa, [7, 8, 9]) ]  function(graphs) 

expected return function(graphs):

([1, 2, 3], [4.0, 5.0, 6.0])  

we can use zip function add corresponding ordinates each ordinate list, using "splat" operator *. tells zip treat each list in ylists argument, zips of lists together, creating list of tuples. first tuple in resulting list contains 1st members of each list in ylist, 2nd tuple in resulting list contains 2nd members of each list in ylist, etc.

#!/usr/bin/env python  ''' find means of graph data '''  def mean_graph(graphs):     abscissa = graphs[0][0]      #extract ordinate lists     ylists = [g[1] g in graphs]      #find means of corresponding ordinates     size = float(len(graphs))     means = [sum(v) / size v in zip(*ylists)]      return abscissa, means   abscissa = range(1, 4) graphs = [     (abscissa, [1, 2, 3]),     (abscissa, [4, 5, 6]),     (abscissa, [7, 8, 9]), ]  print(mean_graph(graphs)) 

output

([1, 2, 3], [4.0, 5.0, 6.0]) 

i developed above code on python 2.6.6. on python 3 can change
size = float(len(graphs))
to
size = len(graphs)


fwiw, it's possible condense mean_graph function 1 line, although make little harder read:

def mean_graph(graphs):     return graphs[0][0], [sum(v) / float(len(graphs)) v in zip(*[g[1] g in graphs])] 

or python 3:

def mean_graph(graphs):     return graphs[0][0], [sum(v) / len(graphs) v in zip(*[g[1] g in graphs])] 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -