'Rewrite dynamically calculation to avoid numpy IndexError: index 31 is out of bounds for axis 0 with size 31

I am trying to calculate this:(x[z + 1] - x[z])

x has the shape of (31, ) and z has the shape of (10000, ). z being indexes from 0 to 30.

The error I think comes from this part: x[z + 1] where it fails when it exceeds the length of the shape (31, )

I have tried to run this in a while loop with the length of x and a counter but this didn't work.

How can I rewrite this to avoid this IndexError of "out of bounds"?



Solution 1:[1]

Do you know np.diff:

np.diff(x)

?

If you want to do it in a clumsy way, you could use slicing:

x[1:] - x[:len(x)-1]

, but I don't know why you would want to do that :-)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DeepKling