1

I tried to build the differences from the values of one element [n] to the next element [n+1] in the same numpy.array.

This must be repeated for all n, I expect n-1 result values.
Furthermore I want to avoid using loops, because loops may be a source of errors numbering the elements.

Now I'm looking for an operation like:

result = array[n+1] - array[n]

for all n.

I tried much similar implementations, but I always get some error messages.

How can I make it work?

4
  • 2
    Welcome to stack overflow, you might want to take a look at how to format code so that it is readable and copy-pastable. Here are the guidelines to ask a good question. As for the answer itself, np.diff(array) does what you ask Commented Jul 6, 2017 at 16:27
  • np.diff() is what I looked for. Sometimes it is very easy with one keyword from an expert. Thank you gionni! Commented Jul 6, 2017 at 16:31
  • You are welcome pal, it can be hard to find what you are looking for in the beginning ;-) Commented Jul 6, 2017 at 16:37
  • @gionni You should post that as an answer Commented Jul 6, 2017 at 19:04

2 Answers 2

3

Numpy's diff() function does what you ask.

Here is an example:

import numpy as np
a = np.arange(10)  # this instantiates a numpy array containing values from 0 to 9
result = np.diff(a)  # if you print this you'll see an array of 1 with length 9

If you want you can use slicing instead (I add this for all newbies, as an example of slicing), as follows:

result = a[1:] - a[:-1]
Sign up to request clarification or add additional context in comments.

Comments

2
x = np.array([2,3,1,0])
result = x[:-1] - x[1:]

Output:

[-1,  2,  1]

Comments

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.