1

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?

7
  • The code is fine, output: [2, 3, 2, 9, 6, 22], "but it doesn't seem to work", can you be more specific? Commented Jul 30, 2014 at 9:17
  • @KobiK When I do the above I am getting result = [1,1,1,1,1,1] Commented Jul 30, 2014 at 9:20
  • @user3397243 That's not possible unless you've an array like [1, 2, 3, ...] Commented Jul 30, 2014 at 9:20
  • @user3397243 can you attach the code? Commented Jul 30, 2014 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. Commented Jul 30, 2014 at 9:28

1 Answer 1

3

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]
Sign up to request clarification or add additional context in comments.

5 Comments

@user3397243 Your code works fine for me, but you should not list comprehension if NumPy already provides a function for this.
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 And what does a contains here?
a contains the numbers of r that have been sliced in 50 bins and b contains the numbers counts within those slices
I have edited my question properly. please take a look

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.