Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have calculated a histogram slice using numpy histogram by N,a = np.histogram(z,bins=50). Now my a contains the values of the 50 slices of z and N contains the number counts within those slices.

I would like to calculate R-r for a

I have tried

result = [R-r for R,r in zip(a[1:],a)]

but it doesn't seem to work. What I am doing wrong here?

share|improve this question
    
The code is fine, output: [2, 3, 2, 9, 6, 22], "but it doesn't seem to work", can you be more specific? –  Kobi K Jul 30 '14 at 9:17
    
@KobiK When I do the above I am getting result = [1,1,1,1,1,1] –  user3397243 Jul 30 '14 at 9:20
    
@user3397243 That's not possible unless you've an array like [1, 2, 3, ...] –  Ashwini Chaudhary Jul 30 '14 at 9:20
    
@user3397243 can you attach the code? –  Kobi K Jul 30 '14 at 9:22
    
@user3397243: Why are you working with the second return value? That's the bin edges. If this were a graphical histogram, you'd be doing your math with the little ticks on the bottom of your graph instead of looking at the height of the bars. –  user2357112 Jul 30 '14 at 9:28

1 Answer 1

up vote 3 down vote accepted

You simply need to use numpy.diff for this:

>>> a = np.array([1,3,6,8,17,23,45])
>>> np.diff(a)
array([ 2,  3,  2,  9,  6, 22])

Edit:

Your code is working fine too, but you should not use list comprehension for this as NumPy already provides a function for this because it is going be both fast and efficient.

>>> a = np.array([1,3,6,8,17,23,45])
>>> [R-r for R,r in zip(a[1:],a)]
[2, 3, 2, 9, 6, 22]
share|improve this answer
    
Thanks, it works! But what is wrong with my code? –  user3397243 Jul 30 '14 at 9:13
    
@user3397243 Your code works fine for me, but you should not list comprehension if NumPy already provides a function for this. –  Ashwini Chaudhary Jul 30 '14 at 9:16
    
The same does not work for a histogram slice!! i.e if I have b,a = np.histogram(r,bins=50) and I say result = np.diff(a) –  user3397243 Jul 30 '14 at 9:21
    
@user3397243 And what does a contains here? –  Ashwini Chaudhary Jul 30 '14 at 9:24
    
a contains the numbers of r that have been sliced in 50 bins and b contains the numbers counts within those slices –  user3397243 Jul 30 '14 at 9:26

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.