Trying to bin one column and sum the other simultaneously. Please help.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • arick1234
    New Member
    • Nov 2011
    • 1

    Trying to bin one column and sum the other simultaneously. Please help.

    I have an array [x,y] where the values of x is ascending and the y values are random. I would like to sum all of the y values together when the x values are within a certain range. I can't show you any code as i dont even know where to start with this but this is the desired effect:-

    Example data:-

    (1, 0.5)
    (2, 5.0)
    (4, 2.0)
    (7, 0.5)
    (8, 0.5)
    (10, 2.5)
    (11, 1.5)
    (15, 3.0)
    (18, 4.0)
    (20, 0.5)
    ...... etc.

    If the range of y is 10. So from y=1 to y=10 and from y=11 to y=20 the x values will be summed within these two bands, I will get a list:-

    11.0, 9.0, ...... etc.

    So far I have been advised to sum all the y values, this gives:-

    Code:
     SELECT ALL
    import numpy, scipy, matplotlib.pylab as plt
    
    mjd1, flux1, error1 = numpy.loadtxt("log_207_band1.dat", usecols=(1,2,3), unpack=True)
    
    x=mjd1
    y=flux1
    z=zip(x,y)
    
    print sum(i[1] for i in z)

    I'm really at a loss of what to do next.

    Thanks.
  • Glenton
    Recognized Expert Contributor
    • Nov 2008
    • 391

    #2
    I'd define my bins first:
    Eg bin=range(10,10 0,10)

    Then make you list of sums:
    Sums=[0]

    Then loop through either adding the y value to the last value (ie Sums[-1]) or appending a new value to Sums (ie Sums.append(0)) according to the value of x.

    Comment

    • Glenton
      Recognized Expert Contributor
      • Nov 2008
      • 391

      #3
      Code:
      bin=10
      sums=[0]
      for x,y in zip(xs,ys):
          if x>bin:
              bin+=10
              sums.append(0)
          sums[-1]+=y
      Should do it.

      Comment

      Working...