shev72 - 5 months ago 22

Python Question

Is there a simple way to get the ratios of consecutive elements of a numpy array?

Basically something similar to numpy.diff(x)?

so if x=[1,2,10,100 ...]

I would like [0.5 ,0.2, 0.1 ...]

ie [x1/x2, x2/x3 , x3/x4]

I know I can do this easily by shifting and dividing, but it seems clumsy compared to numpy.diff(x)

Answer

Using numpy:

```
In [6]: x
Out[6]: array([ 1., 2., 10., 100., 150., 75.])
In [7]: x[:-1]/x[1:]
Out[7]: array([ 0.5 , 0.2 , 0.1 , 0.66666667, 2. ])
```

That might be what you meant when you said "I can do this easily by shifting and dividing", but I don't see anything clumsy about it.